gpt4 book ai didi

testing - Sinon 监视所有方法调用

转载 作者:行者123 更新时间:2023-11-28 20:51:43 25 4
gpt4 key购买 nike

我正在尝试测试是否至少调用了一次特定实例方法。使用 mochasinon。有 2 个类:ABB#renderA#render 中被调用。无法访问测试文件中的 B 实例。

sinon.spy B.prototype, 'render'
@instanceA.render
B.prototype.render.called.should.equal true
B.prototype.render.restore()

这是正确的做法吗?谢谢

最佳答案

你应该这样做:

const chai = require('chai');
const sinon = require('sinon');
const SinonChai = require('sinon-chai');

chai.use(SinonChai);
chai.should();

/**
* Class A
* @type {B}
*/
class A {

constructor(){
this.b = new B();
}


render(){
this.b.render();
}
}


/**
* Class B
* @type {[type]}
*/
class B {

constructor(){

}

render(){
}
}



context('test', function() {

beforeEach(() => {
if (!this.sandbox) {
this.sandbox = sinon.sandbox.create();
} else {
this.sandbox.restore();
}
});

it('should pass',
(done) => {

const a = new A();

const spyA = this.sandbox.spy(A.prototype, 'render');
const spyB = this.sandbox.spy(B.prototype, 'render');

a.render();

spyA.should.have.been.called;
spyB.should.have.been.called;

done();
});

});

您的假设是正确的。您在类的原型(prototype)级别添加 spy 。希望对您有所帮助:)

关于testing - Sinon 监视所有方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43875573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com