在测试AngularJS应用程序的一部分时,它同时使用$timeout和$timeout.cancel,并使用Jasmine的spyOn方法。
describe('<whatever>', function() {
beforeEach(function() {
spyOn(this, '$timeout').andCallThrough();
spyOn(this.$timeout, 'cancel').andCallThrough();
this.createController();
});
it('should <whatever>', function() {
expect(this.$timeout).toHaveBeenCalled();
expect(this.$timeout.cancel).toHaveBeenCalled();
});
});您应该在应用程序代码中遇到以下错误,它使用的是您的测试注入的内容。
TypeError: 'undefined' is not a function (evaluating '$timeout.cancel(timeoutPromise)');发布于 2014-04-09 08:39:37
如果您要在您的测试套件中运行console.log(Object.keys(this.$timeout));,您将看到以下输出;
LOG: ['identity', 'isSpy', 'plan', 'mostRecentCall', 'argsForCall', 'calls', 'andCallThrough', 'andReturn', 'andThrow', 'andCallFake', 'reset', 'wasCalled', 'callCount', 'baseObj', 'methodName', 'originalValue']$timeout是一个AngularJS也在用cancel方法修饰的函数--因为函数是对象。因为这并不是一件普通的事情,茉莉花取代而不是增加$timeout,它的间谍实现-打击$timeout.cancel。
解决这一问题的方法是在cancel被茉莉花的$timeout间谍覆盖后,再将$timeout间谍放回原处,如下所示;
describe('<whatever>', function() {
beforeEach(function() {
spyOn(this.$timeout, 'cancel').andCallThrough();
var $timeout_cancel = this.$timeout.cancel;
spyOn(this, '$timeout').andCallThrough();
this.$timeout.cancel = $timeout_cancel;
this.createController();
});
it('should <whatever>', function() {
expect(this.$timeout).toHaveBeenCalled();
expect(this.$timeout.cancel).toHaveBeenCalled();
});
});发布于 2017-05-12 05:14:04
这对我来说对$interval是有效的,对$timeout也是如此。(茉莉花2)
var $intervalSpy = jasmine.createSpy('$interval', $interval).and.callThrough();
然后我可以同时做两件事:
expect($intervalSpy.cancel).toHaveBeenCalledTimes(1);
expect($intervalSpy).toHaveBeenCalledTimes(1);https://stackoverflow.com/questions/22957097
复制相似问题