我有角度服务功能,我愿意测试:
doSomeTask: function (ids, callback) {
$http.put('/get_job', {'ids': ids}).success(function (data) {
var statusCheck = $interval(function() {
$http.get('check_status?=' + data.job_id).success(function (data) {
if(data.completed) {
$interval.cancel(statusCheck);
// and do something...
}
});
}, 2000);
});
以下测试:
describe('MyService', function() {
var myService;
var $httpBackend;
var $interval;
beforeEach(module('myModule'));
beforeEach(inject(function(_$httpBackend_, _$interval_, $rootScope, MyService) {
$httpBackend = _$httpBackend_;
$interval = _$interval_;
myService = MyService;
}));
describe('doSomeTask', function () {
beforeEach(function () {
$httpBackend.expectPUT("/get_job").respond({ job_id: '123' });
$httpBackend.expectGET("/status_check").respond({ completed: true });
});
it('should do it well', inject(function ($interval) {
var ids = [1,2,3];
myService.doSomeTask(ids);
$httpBackend.flush();
$interval.flush();
}));
});
});
好像我的间隔永远不会被冲洗(第二个期望永远不会得到满足,并且我在间隔体内的断点永远不会被击中)。它似乎也在使用模拟(在flush实现中放置了一些推荐)。 Angular和mocks的版本是相同的......
我做错了什么?我怎样才能刷新我的间隔?
答案 0 :(得分:5)
我认为你必须在刷新间隔后再拨一个$httpBackend.flush()
。测试在代码的这个位置执行日志时是否获得控制台输出:
doSomeTask: function (ids, callback) {
$http.put('/get_job', {'ids': ids}).success(function (data) {
var statusCheck = $interval(function() {
console.log("flushed");
$http.get('check_status?=' + data.job_id).success(function (data) {
if(data.completed) {
$interval.cancel(statusCheck);
// and do something...
}
});
}, 2000);
});
当您在控制台中获得flushed
时,请拨打第二个$httpBackend.flush()
并触发第二个http请求。
it('should do it well', inject(function ($interval) {
var ids = [1,2,3];
myService.doSomeTask(ids);
$httpBackend.flush();
$interval.flush();
// after this call, you should get a 'flushed' in your console
$httpBackend.flush();
// after this call, the second http should fire
}));
要刷新间隔,请指定要像这样刷新的毫秒数:$interval.flush(2000)