2015-10-30 59 views
3

我想单元测试一个Angular.js $timeout来检查它是否被调用了正确的持续时间/延迟值。

断言将是这个样子:

expect($timeout).toHaveBeenCalledWith(n); 

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

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

加上其他几种方法,但我似乎无法得到它的工作。

我采用了棱角分明1.3.20,茉莉花2.3.4

感激地接受任何建议。

回答

3

您可以尝试创建一个模拟超时并设置对间谍的期望值。为了检查第一个参数,你可以使用匹配器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

+0

漂亮的工作。谢谢:) – atwright147

+0

@ atwright147不客气。 :) – PSL