我想要对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
收到的任何建议都很感激。
发布于 2015-10-30 13:26:39
您可以尝试为超时创建一个模拟,并设置对间谍的期望。为了检查第一个参数,可以使用matcher 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);
});
});演示
如果是指令,就用你的间谍覆盖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);
});演示
https://stackoverflow.com/questions/33436313
复制相似问题