gpt4 book ai didi

angularjs - Jasmine 单元测试 $timeout (expect($timeout).toHaveBeenCalledWith(n);)

转载 作者:行者123 更新时间:2023-12-04 02:16:29 26 4
gpt4 key购买 nike

我想对 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

非常感谢收到的任何建议。

最佳答案

您可以尝试为超时创建模拟并在 spy 上设置期望。要检查第一个参数,您可以使用匹配器 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

如果它是一个指令,只需用你的 spy 覆盖 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

关于angularjs - Jasmine 单元测试 $timeout (expect($timeout).toHaveBeenCalledWith(n);),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33436313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com