gwh*_*whn 21 jasmine angularjs
我使用AngularJS的v1.2.0-rc.3和Jasmine测试框架.
我试图断言控制器调用服务方法.service方法返回一个promise.控制器看起来像这样:
angular.module('test', [])
.controller('ctrl', ['$scope', 'svc', function ($scope, svc) {
$scope.data = [];
svc.query()
.then(function (data) {
$scope.data = data;
});
}]);
Run Code Online (Sandbox Code Playgroud)
我想测试在解析服务方法的延迟时将数据分配给范围.我已经为服务创建了一个模拟,单元测试看起来像这样:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
我希望调用svc的查询方法,但显然它没有.
我按照本指南嘲笑单元测试中的承诺.
我究竟做错了什么?
gwh*_*whn 28
我似乎把我的间谍放在了错误的地方.当我将它放在beforeEach中时,测试通过.
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
});
}));
Run Code Online (Sandbox Code Playgroud)