javascript 对茉莉花间谍的重置调用不返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31539736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reset call on Jasmine spy does not return
提问by Jorn
I'm using a Jasmine (2.2.0) spy to see if a certain callback is called.
我正在使用 Jasmine (2.2.0) 间谍来查看是否调用了某个回调。
Test code:
测试代码:
it('tests', function(done) {
var spy = jasmine.createSpy('mySpy');
objectUnderTest.someFunction(spy).then(function() {
expect(spy).toHaveBeenCalled();
done();
});
});
This works as expected. But now, I'm adding a second level:
这按预期工作。但是现在,我要添加第二个级别:
it('tests deeper', function(done) {
var spy = jasmine.createSpy('mySpy');
objectUnderTest.someFunction(spy).then(function() {
expect(spy).toHaveBeenCalled();
spy.reset();
return objectUnderTest.someFunction(spy);
}).then(function() {
expect(spy.toHaveBeenCalled());
expect(spy.callCount).toBe(1);
done();
});
});
This test never returns, because apparently the done
callback is never called. If I remove the line spy.reset()
, the test does finish, but obviously fails on the last expectation. However, the callCount
field seems to be undefined
, rather than 2
.
这个测试永远不会返回,因为显然done
回调永远不会被调用。如果我删除该行spy.reset()
,测试确实完成,但显然在最后的期望上失败了。但是,该callCount
字段似乎是undefined
,而不是2
。
回答by Eitan Peer
The syntax for Jasmine 2 is different than 1.3 with respect to spy functions. See Jasmine docs here.
Jasmine 2 的语法在间谍函数方面与 1.3 不同。请参阅此处的Jasmine 文档。
Specifically you reset a spy with spy.calls.reset();
具体来说,你重置了一个间谍 spy.calls.reset();
This is how the test should look like:
测试应该是这样的:
// Source
var objectUnderTest = {
someFunction: function (cb) {
var promise = new Promise(function (resolve, reject) {
if (true) {
cb();
resolve();
} else {
reject(new Error("something bad happened"));
}
});
return promise;
}
}
// Test
describe('foo', function () {
it('tests', function (done) {
var spy = jasmine.createSpy('mySpy');
objectUnderTest.someFunction(spy).then(function () {
expect(spy).toHaveBeenCalled();
done();
});
});
it('tests deeper', function (done) {
var spy = jasmine.createSpy('mySpy');
objectUnderTest.someFunction(spy).then(function () {
expect(spy).toHaveBeenCalled();
spy.calls.reset();
return objectUnderTest.someFunction(spy);
}).then(function () {
expect(spy).toHaveBeenCalled();
expect(spy.calls.count()).toBe(1);
done();
});
});
});
See fiddle here
在这里看到小提琴
回答by Steve Brush
Another way to write it:
另一种写法:
spyOn(foo, 'bar');
expect(foo.bar).toHaveBeenCalled();
foo.bar.calls.reset();