我正在为角度控制器编写茉莉花测试用例,这些用例具有一个具有一系列应解决的承诺的初始化函数:
(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的块。
答案 0 :(得分:0)
这就是我要做的:
首先,模拟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);
});