Wor*_*red 43 javascript jasmine angularjs
我在我的一个角度服务中有一个函数,我希望定期重复调用它.我想用$ timeout来做这件事.它看起来像这样:
var interval = 1000; // Or something
var _tick = function () {
$timeout(function () {
doStuff();
_tick();
}, interval);
};
_tick();
Run Code Online (Sandbox Code Playgroud)
我对如何用Jasmine进行单元测试感到困惑 - 我该怎么做?如果我使用$timeout.flush()
那么函数调用无限期地发生.如果我使用Jasmine的模拟时钟,$timeout
似乎不受影响.基本上如果我能让这个工作,我应该好好去:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
这两个版本有用,但不能帮助我:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
提前致谢!
mat*_*sko 52
不要使用Jasmine的时钟进行测试异步.相反,用于$timeout.flush()
同步维护测试流程.设置可能有点棘手,但一旦得到它,您的测试将更快,更受控制.
以下是使用此方法进行测试的示例:https: //github.com/angular/angular.js/blob/master/test/ngAnimate/animateSpec.js#L618
Bee*_*eez 45
@ matsko的回答让我走上了正确的道路.我以为我会发布我的"完整"解决方案,以便更容易找到答案.
angular.module("app").service("MyService", function() {
return {
methodThatHasTimeoutAndReturnsAPromise: function($q, $timeout) {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve(5);
}, 2000);
return deferred.promise;
}
};
});
Run Code Online (Sandbox Code Playgroud)
describe("MyService", function() {
var target,
$timeout;
beforeEach(inject(function(_$timeout_, MyService) {
$timeout = _$timeout_;
target = MyService;
}));
beforeEach(function(done) {
done();
});
it("equals 5", function(done) {
target.methodThatHasTimeoutAndReturnsAPromise().then(function(value) {
expect(value).toBe(5);
done();
});
$timeout.flush();
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35488 次 |
最近记录: |