【问题标题】:Jasmine unit testing $timeout (expect($timeout).toHaveBeenCalledWith(n);)Jasmine 单元测试 $timeout (expect($timeout).toHaveBeenCalledWith(n);)
【发布时间】:2015-10-30 12:45:59
【问题描述】:

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

断言看起来像这样:

expect($timeout).toHaveBeenCalledWith(n);

我的 Angular 代码大致如下所示:

$timeout(function() {
    // do something
}, attrs.timeout || 30000);

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

我试过这样的装饰器:

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

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

我正在使用 Angular 1.3.20,Jasmine 2.3.4

任何建议都非常感谢。

【问题讨论】:

    标签: angularjs unit-testing timeout jasmine


    【解决方案1】:

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

    例子:

    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);
      });
    
    });
    

    Demo

    如果它是一个指令,只需用你的间谍覆盖 timeout

    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);
      });
    

    Demo

    【讨论】:

    • 工作得很好。谢谢你:)
    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多