我的生产代码有这段逻辑,是从 CoffeeScript 编译的:
results = [];
results.push(slowOpA());
results.push(slowOpB());
results.push(slowOpC());
results = _.flatten(results);
$.when.apply($, results).then(onComplete).fail(onError).always(function() {
$(document).trigger('stop')
});
我希望这首先按顺序调用所有 slowOp* 方法,然后调用其中一个onComplete
或仅调用onError
一次,最后仅调用always
一次。这就是我用 Jasmine 测试的内容:
@stopSpy = jasmine.createSpy '<stopSpy>'
$(document).bind 'stop', @stopSpy
...
@lastPromise = new $.Deferred()
spyOn('slowOpA').andReturn new $.Deferred().resolve()
spyOn('slowOpB').andReturn new $.Deferred().resolve()
spyOn('slowOpC').andReturn @lastPromise
...
@lastPromise.resolve()
expect(@stopSpy).toHaveBeenCalledOnce()
100 次中有 99 次有效,但时不时地会收到 2 或 3 个调用:
Expected spy on <stopSpy> to have been called once, but was called '2' times
我错过了什么吗?或者这是 jQuery/Jasmine 中一些模糊的竞争条件?