[英]Mocking $q.all in jasmine for angularjs controller
我正在为角度控制器编写茉莉花测试用例,这些用例具有一个具有一系列应解决的承诺的init函数:
(function () {
angular.controller("xyz", ['$scope', "Utility", "Api",
function ($scope, Utility, Api) {
var locals = $scope.locals = {
id: 1,
amount: 2,
products: 3
};
function init() {
locals.busyPromise = Utility.resolveAll(
{
name: 'a',
promise: Api.get,
then: function (response) { locals.id = 2; }
},
{
name: 'b',
promise: Api.find,
then: function (response) { locals.amount = 4; }
}
).then(function (response) { locals.products = 6; });
}
init();
}
])
})();
Utility是一个外部脚本,用于解析数组中的每个promise,并执行它们的then函数以设置本地属性。 数组中的所有promise解析后,它将移至resolveAll函数并执行它。
我的问题是,当在Jasmine中注入依赖项时,我们如何模拟Utility.resolveAll。 就我而言,无论我尝试什么,它都永远不会进入单个promise的then块,而直接进入resolveAll的then块。
在这里我会做什么:
首先,如果有的话,请模拟Utility
和Api
服务
let Utility, Api;
beforeEach(() => {
Utility = jasmine.createSpyObj('Utility', ['resolveAll']);
Api = jasmine.createSpyObj('Api', ['find', 'get']);
});
然后在测试中:
it('should test component startup', function() {
let resolveObjects;
Utility.resolveAll.and.callFake(function(...args) {
resolveObjects = args; // save all arguments, passed to `resolveAll` method
return $q.when();
})
$scope = $rootScope.$new();
let controller = $controller('xyz', {$scope, Utility, Api});
$rootScope.digest(); // resolve $q.when so you can test overall promise
expect($scope.locals.products).toBe(6); // test overall promise
// now, test all the arguments
// 0
expect(resolveObjects[0].name).toBe('a');
resolveObjects[0].promise();
expect(Api.get).toHaveBeenCalledTimes(1);
resolveObjects[0].then();
expect($scope.locals.id).toBe(4);
// 1
expect(resolveObjects[1.name).toBe('b');
resolveObjects[1].promise();
expect(Api.find).toHaveBeenCalledTimes(1);
resolveObjects[1].then();
expect($scope.locals.products).toBe(4);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.