首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >茉莉花单元测试$timeout (expect($timeout).toHaveBeenCalledWith(n);)

茉莉花单元测试$timeout (expect($timeout).toHaveBeenCalledWith(n);)
EN

Stack Overflow用户
提问于 2015-10-30 12:45:59
回答 1查看 2.8K关注 0票数 3

我想要对Angular.js $timeout进行单元测试,以检查它是否已被调用,并具有正确的持续时间/延迟值。

断言如下所示:

代码语言:javascript
复制
expect($timeout).toHaveBeenCalledWith(n);

我的角度代码大致如下所示:

代码语言:javascript
复制
$timeout(function() {
    // do something
}, attrs.timeout || 30000);

我希望确保在没有覆盖(attrs.timeout)的情况下,它是用30000调用的,并且使用该覆盖调用它。

我试过这样的装饰师:

代码语言:javascript
复制
// from: http://stackoverflow.com/a/21536245/633056
beforeEach(module(function($provide) {
    $provide.decorator('$timeout', function($delegate) {
        return jasmine.createSpy($delegate);
    });
}));

加上其他几种方法,但我似乎无法让它发挥作用。

我用的是角1.3.20,茉莉花2.3.4

收到的任何建议都很感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-30 13:26:39

您可以尝试为超时创建一个模拟,并设置对间谍的期望。为了检查第一个参数,可以使用matcher jasmine.any(Function)和带有预期延迟的第二个参数。

示例:

代码语言:javascript
复制
describe('Ctrl', function() {
  beforeEach(module('test-app'));
  var ctrl, timeout;
  beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();

    //Create Spy
    timeout = jasmine.createSpy('$timeout');

    ctrl = $controller('loadingCtr', {
      '$timeout': timeout
    });

    $rootScope.$digest();
  }));

  //Your expectations
  it('should call timeout with passed in delay', function() {
    ctrl.callTimeout(1000);
    expect(timeout).toHaveBeenCalledWith(jasmine.any(Function), 1000);
  });
  it('should call timeout with default delay', function() {
    ctrl.callTimeout();
    expect(timeout).toHaveBeenCalledWith(jasmine.any(Function), 30000);
  });

});

演示

如果是指令,就用你的间谍覆盖timeout

代码语言:javascript
复制
var dir, 
      timeout = jasmine.createSpy('$timeout'), scope;

  beforeEach(module('test-app', function ($provide) {
       $provide.value('$timeout', timeout);
   }));

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();
    $compile('<test-timeout timeout="6000"></test-timeout>')(scope);
    scope.$apply();
  }));

  it('should call timeout with passed in delay', function() {
     expect(timeout).toHaveBeenCalledWith(jasmine.any(Function), 6000);
  });

演示

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33436313

复制
相关文章

相似问题

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