首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJS: spyOn,$timeout和$timeout.cancel

AngularJS: spyOn,$timeout和$timeout.cancel
EN

Stack Overflow用户
提问于 2014-04-09 08:39:37
回答 2查看 2.5K关注 0票数 1

在测试AngularJS应用程序的一部分时,它同时使用$timeout$timeout.cancel,并使用Jasmine的spyOn方法。

代码语言:javascript
复制
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();
  });

});

您应该在应用程序代码中遇到以下错误,它使用的是您的测试注入的内容。

代码语言:javascript
复制
TypeError: 'undefined' is not a function (evaluating '$timeout.cancel(timeoutPromise)');
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-09 08:39:37

如果您要在您的测试套件中运行console.log(Object.keys(this.$timeout));,您将看到以下输出;

代码语言:javascript
复制
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间谍放回原处,如下所示;

代码语言:javascript
复制
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();
  });

});
票数 3
EN

Stack Overflow用户

发布于 2017-05-12 05:14:04

这对我来说对$interval是有效的,对$timeout也是如此。(茉莉花2)

var $intervalSpy = jasmine.createSpy('$interval', $interval).and.callThrough();

然后我可以同时做两件事:

代码语言:javascript
复制
expect($intervalSpy.cancel).toHaveBeenCalledTimes(1);
expect($intervalSpy).toHaveBeenCalledTimes(1);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22957097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档