gpt4 book ai didi

javascript - Jasmine spyOn 函数在回调中不起作用

转载 作者:行者123 更新时间:2023-11-30 15:41:50 29 4
gpt4 key购买 nike

如果在回调函数中调用该方法,则在对象上使用 spyOn 似乎会失败。 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);
});

这个将失败并出现错误“Expected 0 to equal 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 spyOn 函数在回调中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40688401/

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