如果在回调函数中调用该方法,则在对象上使用 spy On似乎会失败。 jasmine 不会注意到回调中对该方法的任何调用。
请参阅下面的代码,我在 child.print() 方法上创建了一个 spy 。如果我在回调(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);
});
我试图在回调中设置一个断点,似乎我们正在测试的函数周围的 spy 包装消失了,这就是表面上的原因。有人可以解释为什么会发生这种情况以及正确的方法吗?
感谢您的阅读~
最佳答案
您需要使用 Jasmine 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);
});
关于javascript - Jasmine spy 功能在回调中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40688401/