0
我想測試我的控制器中正在調用我的注入服務。注入服務的單元測試控制器
login.controller.js
angular.module('exampleModule')
.controller('LoginCtrl', ['$state', 'AuthService',
function($state, AuthService) {
var self = this;
self.submit = function() {
AuthService.login(self.credentials)
.then(function(res) {
console.log('success');
$state.go('home');
}, function(res) {
if (res.status === 400) {
console.log('error')
}
});
};
}
]);
login.service.js
angular.module('exampleModule')
.factory('AuthService', ['$http',
function($http) {
var authService = {};
authService.login = function(credentials) {
return $http.post('/api/authenticate', credentials);
.then(function(res) {
return res;
});
};
return authService;
}
]);
login.controller.test.js
describe('Controller: LoginCtrl', function() {
beforeEach(module('exampleModule'));
var ctrl, authService;
beforeEach(inject(function($controller, AuthService){
ctrl = $controller('LoginCtrl');
authService = AuthService;
}));
describe('submit function', function() {
beforeEach(function(){
ctrl.submit();
});
it('should call AuthService', function() {
expect(authService.login).toHaveBeenCalled();
});
});
});
如何正確測試AuthService.login
是否被調用?有了辦法,我注入AuthService
到我的測試,我得到這些錯誤:
TypeError: 'undefined' is not an object (evaluating 'AuthService.login(self.credentials).then')