问题描述
我在一个角度服务中有一个函数,希望以固定的时间间隔重复调用该函数.我想使用$ timeout做到这一点.看起来像这样:
I have a function inside one of my angular services that I'd like to be called repeatedly at a regular interval. I'd like to do this using $timeout. It looks something like this:
var interval = 1000; // Or something
var _tick = function () {
$timeout(function () {
doStuff();
_tick();
}, interval);
};
_tick();
目前,我很困惑如何与Jasmine进行单元测试-我该怎么做?如果我使用 $ timeout.flush()
,则函数调用将无限期地发生.如果我使用Jasmine的模拟时钟,则 $ timeout
似乎不受影响.基本上,如果我能解决这个问题,那我应该很好:
I'm stumped on how to unit test this with Jasmine at the moment - How do I do this? If I use $timeout.flush()
then the function calls occur indefinitely. If I use Jasmine's mock clock, $timeout
seems to be unaffected. Basically if I can get this working, I should be good to go:
describe("ANGULAR Manually ticking the Jasmine Mock Clock", function() {
var timerCallback, $timeout;
beforeEach(inject(function($injector) {
$timeout = $injector.get('$timeout');
timerCallback = jasmine.createSpy('timerCallback');
jasmine.Clock.useMock();
}));
it("causes a timeout to be called synchronously", function() {
$timeout(function() {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.Clock.tick(101);
expect(timerCallback).toHaveBeenCalled();
});
});
这两个变体有效,但对我没有帮助:
These two variations work, but do not help me:
describe("Manually ticking the Jasmine Mock Clock", function() {
var timerCallback;
beforeEach(function() {
timerCallback = jasmine.createSpy('timerCallback');
jasmine.Clock.useMock();
});
it("causes a timeout to be called synchronously", function() {
setTimeout(function() {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.Clock.tick(101);
expect(timerCallback).toHaveBeenCalled();
});
});
describe("ANGULAR Manually flushing $timeout", function() {
var timerCallback, $timeout;
beforeEach(inject(function($injector) {
$timeout = $injector.get('$timeout');
timerCallback = jasmine.createSpy('timerCallback');
}));
it("causes a timeout to be called synchronously", function() {
$timeout(function() {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
$timeout.flush();
expect(timerCallback).toHaveBeenCalled();
});
});
提前谢谢!
推荐答案
请勿使用Jasmine的时钟使您的测试异步.而是使用 $ timeout.flush()
同步维护测试流程.设置起来可能有些棘手,但是一旦安装成功,您的测试就会更快,更受控制.
Do not make your test Async by using Jasmine's clock. Instead, use $timeout.flush()
to synchronously maintain the flow of the test. It may be a bit tricky to setup, but once you get it then your tests will be faster and more controlled.
以下是使用此方法进行测试的示例: https://github.com/angular/angular.js/blob/master/test/ngAnimate/animateSpec.js#L618
Here's an example of a test that does it using this approach:https://github.com/angular/angular.js/blob/master/test/ngAnimate/animateSpec.js#L618
这篇关于在Jasmine' s模拟时钟中使用$ timeout的单元测试Angular Service的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!