Jasmine spyOn函数在回调函数中不起作用
问题描述:
如果在回调函数中调用该方法,则在对象上使用spyOn似乎会失败。茉莉花不会注意到任何回调中的方法调用。Jasmine spyOn函数在回调函数中不起作用
请参阅下面的代码,我在child.print()方法上创建了一个间谍。如果我在回调(的setTimeout)调用child.print(),它不工作:
it('test', function() {
const child = {
print: function() {
console.log('child');
}
};
spyOn(child, 'print');
const parent = {
callChildInCallback: function() {
setTimeout(()=> child.print(), 1000);
}
};
parent.callChildInCallback();
expect(child.print.calls.count()).toEqual(1);
});
这人会失败,出现错误“预计0至1等于”
但是如果我直接调用它,它的工作原理:
it('test', function() {
const child = {
print: function() {
console.log('child');
}
};
spyOn(child, 'print');
const parent = {
callChild: function() {
child.print();
}
};
parent.callChild();
expect(child.print.calls.count()).toEqual(1);
});
我试图断点设置步入回调,似乎围绕我们正在测试是走功能的间谍包,这是该表面上的原因。有人可以解释为什么会发生这种情况,以及正确的方法吗?
感谢您的阅读〜
答
你需要使用茉莉花clock与超时功能工作
it('test', function() {
jasmine.clock().install();
const child = {
print: function() {
console.log('child');
}
};
spyOn(child, 'print').and.callThrough();
const parent = {
callChildInCallback: function() {
setTimeout(function() {
child.print()
}, 1000);
}
};
parent.callChildInCallback();
jasmine.clock().tick(1001);
expect(child.print.calls.count()).toEqual(1);
});