gpt4 book ai didi

angularjs - $q.all 的 Jasmine 单元测试

转载 作者:行者123 更新时间:2023-12-01 06:25:58 25 4
gpt4 key购买 nike

我的 Controller 看起来像:

$q.all([test1Factory.queryAll().$promise, test2Factory.queryAll().$promise,test3Factory.queryAll().$promise]).then(function(results) { 
$scope.testList1 = results[0];
$scope.testList2 = results[1];
$scope.testList3 = results[2];
});

我试着关注这个 How to resolve $q.all promises in Jasmine unit tests?

但在我的情况下,它给出的错误是
TypeError: 'undefined' is not an object (evaluating 'test1Factory.queryAll().$promise')
$q.all期望一个 Promises 数组,如果它们不是 Promises,它们将被视为立即完成。所以我使用了 $promise 的资源。我从这里得到的

Angular Resource calls and $q

有人可以帮我解决这个错误。

最佳答案

如果您真的想测试返回值,您必须为每个服务创建一个 Jasmine spy 对象。每个 spy 对象都可以模拟一个特定的方法 (queryAll),然后在 promise 解析时返回一些测试数据。

describe('$q.all', function() {
beforeEach(function() {
return module('yourNgModule');
});
beforeEach(inject(function($injector) {
var ctrl, q, rootScope, scope, test1Factory, test2Factory, test3Factory;
q = $injector.get('$q');
rootScope = $injector.get('$rootScope');
scope = rootScope.$new();
test1Factory = jasmine.createSpyObj('test1Factory', ['queryAll']);
test2Factory = jasmine.createSpyObj('test2Factory', ['queryAll']);
test3Factory = jasmine.createSpyObj('test3Factory', ['queryAll']);
test1Factory.queryAll.and.returnValue(q.when(1));
test2Factory.queryAll.and.returnValue(q.when(2));
test3Factory.queryAll.and.returnValue(q.when(3));
ctrl = $injector.get('$controller').controller('yourNgController', {
$scope: scope,
$q: q,
test1Factory: test1Factory,
test2Factory: test2Factory,
test3Factory: test3Factory
});
rootScope.$digest();
}));
return it('returns values for all promises passed to $q.all', function() {
expect(scope.testList1).toEqual(1);
expect(scope.testList2).toEqual(2);
expect(scope.testList3).toEqual(3);
});
});

关于angularjs - $q.all 的 Jasmine 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com