如何使用 Jasmine 测试调用返回承诺的服务方法的 AngularJS 控制器 [英] How to test with Jasmine an AngularJS controller that calls service method that returns promise
问题描述
我正在使用带有 Jasmine 测试框架的 AngularJS v1.2.0-rc.3.
I am using v1.2.0-rc.3 of AngularJS with Jasmine test framework.
我试图断言控制器调用服务方法.服务方法返回一个承诺.控制器看起来像这样:
I am trying to assert that a controller calls a service method. The service method returns a promise. The controller looks like this:
angular.module('test', [])
.controller('ctrl', ['$scope', 'svc', function ($scope, svc) {
$scope.data = [];
svc.query()
.then(function (data) {
$scope.data = data;
});
}]);
我想测试当服务方法的 deferred 被解析时数据是否被分配到范围.我为服务创建了一个模拟,单元测试如下所示:
I want to test that data is assigned to the scope when the service method's deferred is resolved. I have created a mock for the service and the unit test looks like this:
describe('ctrl', function () {
var ctrl, scope, svc, def, data = [{name: 'test'}];
beforeEach(module('test'));
beforeEach(inject(function($controller, $rootScope, $q) {
svc = {
query: function () {
def = $q.defer();
return def.promise;
}
};
scope = $rootScope.$new();
controller = $controller('ctrl', {
$scope: scope,
svc: svc
});
}));
it('should assign data to scope', function () {
spyOn(svc, 'query').andCallThrough();
deferred.resolve(data);
scope.$digest();
expect(svc.query).toHaveBeenCalled();
expect(scope.data).toBe(data);
});
});
我希望调用 svc 的查询方法,但显然没有.
I expect the query method of svc to be called, but apparently it hasn't.
我按照this指南在单元测试中模拟承诺.
I followed this guide to mocking promises in unit tests.
我做错了什么?
推荐答案
看来我把我的间谍放在了错误的地方.当我把它放在 beforeEach 中时,测试通过了.
It seems I was placing my spy in the wrong place. When I place it in the beforeEach, the test passes.
beforeEach(inject(function($controller, $rootScope, $q) {
svc = {
query: function () {
def = $q.defer();
return def.promise;
}
};
spyOn(svc, 'query').andCallThrough();
scope = $rootScope.$new();
controller = $controller('ctrl', {
$scope: scope,
svc: svc
});
}));
这篇关于如何使用 Jasmine 测试调用返回承诺的服务方法的 AngularJS 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!