我需要测试这个功能,
我看到各种帖子,但我可以使它有效
我尝试过'完成'回调也是
我尝试将$ apply调用放在它外面
testfile的
describe('description', function() {
var asi;
var root;
var res;
beforeEach(module('moduloPrueba'));
beforeEach(inject(function (asincronico, $rootScope) {
asi = asincronico;
root = $rootScope;
})
);
it('uno', function(){
asi.tes().then(function(po){
res = po;
});
root.$digest();
expect(res).toBe(9);
});
});
服务
angular.module('moduloPrueba', [])
.factory('asincronico', function($q) {
return {
tes:tes,
};
function tes(){
var deferred = $q.defer();
setTimeout(function () {
deferred.resolve(9);
}, 500);
return deferred.promise;
}
});
答案 0 :(得分:1)
此时你并没有等待承诺:
it('uno', function(){
asi.tes().then(function(po){
res = po;
});
root.$digest();
expect(res).toBe(9);
});
根$消化();并期望(res).toBe(9);在asi.tes()之后立即调用。 您可以将函数标记为异步并等待承诺:
it('uno', async function(){
res = await asi.tes();
root.$digest();
expect(res).toBe(9);
});
答案 1 :(得分:1)
首先,您应该使用color
angularjs服务而不是setTimeout。
您可以使用$timeout
$timeout.flush();
});
以下是工作示例:$timeout async test in angularjs