問題描述
我的一個 Angular 服務中有一個函數,我希望定期重復調用該函數.我想使用 $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
這篇關于使用 $timeout 和 Jasmine 的模擬時鐘的單元測試 Angular 服務的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!