我上课
class Dummy {
constructor() {
this.prop1 = null;
this.prop2 = null;
this.prop3 = setInterval(() => {
this.method1()
}, 1000);
}
method1() {
// Method logic
}
}
var dummyObject = new Dummy();
module.exports = dummyObject;
我想编写测试以验证method1
每隔1秒被调用一次。
以下是测试代码
const dummyObject = require('./dummy.js');
describe("Test setInterval", function () {
it("Test setInterval", function () {
const clock = sinon.useFakeTimers();
const spy = sinon.spy(dummyObject, 'method1');
clock.tick(1001);
expect(spy.calledOnce).to.be.true;
clock.restore();
})
})
但是,当我运行测试时,出现错误“ Expert false to equal to true”,并且在进一步挖掘时,我意识到我无法监视通过setInterval调用的方法。
请分享对我可以做些什么来测试这种情况的想法?
答案 0 :(得分:1)
这将无法按您希望的方式工作,因为在需要模块时已经调用了方法(method1
),因此以后没有机会在测试中对其进行监视。
我建议重构您的模块以导出类,而不是如下实例:
module.exports = class Dummy {
constructor() {
this.prop1 = null;
this.prop2 = null;
this.prop3 = setInterval(() => {
this.method1()
}, 1000);
}
method1() {
// Method logic
}
}
然后在测试中,在实例化该方法之前,需要该类并监视该方法:
const sinon = require('sinon');
const Dummy = require('./dummy.js');
describe("Test setInterval", function () {
it("Test setInterval", function () {
const clock = sinon.useFakeTimers();
// Spy on the method using the class' prototype
const spy = sinon.spy(Dummy.prototype, 'method1');
// Initialize the class and make sure its `constructor` is called after you spied on the method
new Dummy();
clock.tick(1001);
expect(spy.calledOnce).to.be.true;
clock.restore();
})
})