[英]Why is this async Jasmine test failing?
Why is this test failing, saying that the onSuccess
spy was never called? 为什么此测试失败,并说从未调用过onSuccess
间谍?
it('should correctly call the success callback',function(done)
{
const callbacks={
onSuccess:function()
{
console.log('OK');
done();
},
onError:function()
{
console.log('ERR');
done();
}
};
spyOn(callbacks,'onSuccess').and.callThrough();
spyOn(callbacks,'onError').and.callThrough();
doSomethingAsync(callbacks.onSuccess,callbacks.onError);
expect(callbacks.onSuccess).toHaveBeenCalled();
expect(callbacks.onError).not.toHaveBeenCalled();
});
When running the test, I get an error saying Expected spy onSuccess to have been called.
运行测试时,我收到一条错误消息Expected spy onSuccess to have been called.
. 。
Right above that, there's a console log saying "OK", meaning that the spy was called and that it called through. 在此之上,有一个控制台日志,上面写着“ OK”,表示间谍已被调用并被调用。
It's difficult to assert that one callback is called and another one isn't without stubbing doSomethingAsync
or its internals. 很难断言一个回调已被调用,而另一个回调并非不对doSomethingAsync
或其内部进行了处理。
Here's a contrived edge case: 这是一个人为的边缘情况:
function doSomethingAsync(onSuccess, onError) {
setTimeout(function() {
onSuccess('hello');
}, 500);
setTimeout(function() {
onError(new Error('foo'));
}, 1000);
}
(so it calls onSuccess
after half a second, and onError
after a second) (因此,它在半秒钟后调用onSuccess
在一秒钟后调用onError
)
If you assert, in the onSuccess
handler, that onError
hasn't been called, the test will pass, even though onError
is getting called (albeit half a second later). 如果你断言,在onSuccess
处理程序,即onError
还没有被调用,测试会通过,即使onError
获取调用(虽然半秒后)。
This is something that you cannot easily work around, unless (as stated before) you stub (the internals of) doSomethingAsync
. 除非您(如前所述)对doSomethingAsync
(的内部)进行存根,否则这是您不容易解决的问题。
If you simply want to test if doSomethingAsync
calls the right handler, you can shorten your test case to this (provided that it's not strictly necessary to call the handlers in your callbacks
object): 如果您只是想测试doSomethingAsync
调用了正确的处理程序,则可以将测试用例缩短为此(前提是并非严格必须在callbacks
对象中调用处理程序):
it('should correctly call the success callback',function(done) {
doSomethingAsync(done, done.fail);
});
(this doesn't catch doSomethingAsync
calling both handlers, though; if it calls onSuccess
before onError
, the test will pass). (不过,这不会捕获同时调用两个处理程序的doSomethingAsync
;如果它在onError
之前调用onSuccess
,则测试将通过)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.