我试图检查是否已调用带有promise的方法
这是我的控制器
app.controller('StoresListController', function ($scope, StoresService) {
$scope.getStores = function () {
StoresService.getStores().then(function (data) {
$scope.stores = data.data;
});
};
$scope.getStores();
$scope.deleteStore = function (id) {
StoresService.deleteStore(id).then(function () {
$scope.getStores();
});
};
})
和我的测试
beforeEach(inject(function($rootScope, $controller, $q) {
rootScope = $rootScope;
scope = $rootScope.$new();
controller = $controller;
serviceMock = {
getStores: function(){
// mock promise
var deferred = $q.defer();
deferred.resolve({data : 'foo'});
return deferred.promise;
},
deleteStore : function(){
var deferred = $q.defer();
deferred.resolve({data : 'foo'});
return deferred.promise;
}
}
spyOn(serviceMock,'getStores').and.callThrough();
controller("StoresListController", {$scope: scope, StoresService: serviceMock});
}));
it('should call scope.getStores', function(){
scope.$digest();
expect(scope.getStores).toHaveBeenCalled()
});
it('should call scope.getStores afeter scope.deleteStore', function(){
scope.deleteStore(1)
scope.$digest();
expect(scope.getStores.call.count).toBe(2)
});
});
我得到了错误:期待一个间谍,但得到了功能。对于第一个失败的第一个,我做错了什么?
答案 0 :(得分:0)
发生此错误是因为您将Spy添加到serviceMock对象而不是StoresService。你也可以在间谍上调用callFake方法来模拟服务
// Notice that you have to inject the StoresService here
beforeEach(inject(function($rootScope, $controller, $q, StoresService) {
rootScope = $rootScope;
scope = $rootScope.$new();
controller = $controller;
serviceMock = {
getStores: function() {
// mock promise
var deferred = $q.defer();
deferred.resolve({ data: 'foo' });
return deferred.promise;
},
deleteStore: function() {
var deferred = $q.defer();
deferred.resolve ({ data: 'foo' });
return deferred.promise;
}
}
// Spy for getStores method
spyOn(StoresService, 'getStores').and.callFake(serviceMock.getStores);
// Spy for deleteStore method
spyOn(StoresService, 'deleteStore').and.callFake(serviceMock.deleteStore);
// Removed the local injection of StoresService
controller("StoresListController", { $scope: scope });
}));
it('should call scope.getStores', function() {
scope.$digest();
expect(scope.getStores).toHaveBeenCalled()
});
it('should call scope.getStores afeter scope.deleteStore', function() {
scope.deleteStore(1)
scope.$digest();
expect(scope.getStores.call.count).toBe(2)
});