'use strict'
webApp.controller 'NavigationController', [
'$scope'
'$rootScope'
'UserService'
($scope, $rootScope, UserService) ->
$scope.init = ->
UserService.isAuthenticated().then (authenticated) ->
$scope.isAuthenticated = authenticated
$scope.init()
]
如果从spyOn
调用isAuthenticated
,我想向UserService
编写测试。在我的beforeEach
中,我有:
beforeEach ->
module 'webApp'
inject ($injector) ->
$httpBackend = $injector.get '$httpBackend'
$q = $injector.get '$q'
$rootScope = $injector.get '$rootScope'
$scope = $rootScope.$new()
$controller = $injector.get '$controller'
UserServiceMock =
isAuthenticated: ->
deferred = $q.defer()
deferred.promise
controller = $controller 'AboutUsController',
'$scope': $scope
'$rootScope': $rootScope
'UserService': UserServiceMock
$httpBackend.whenGET('/api/v1/session').respond 200
任何帮助将不胜感激..谢谢
答案 0 :(得分:5)
在UserServiceMock
中调用isAuthenticated时,您可以将变量设置为true。 e.g:
var isAuthenticatedCalled;
var controller;
beforeEach(function() {
isAuthenticatedCalled = false;
module('webApp');
inject(function($injector) {
//...
UserServiceMock = {
isAuthenticated: function() {
isAuthenticatedCalled = true;
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
}
};
controller = $controller('AboutUsController', {
'$scope': $scope,
'$rootScope': $rootScope,
'UserService': UserServiceMock
});
// ...
});
});
it('should call isAuthenticated', function() {
expect(isAuthenticatedCalled).toBe(true)
});
另外,您可以使用Jasmine的spyOn
功能。
UserServiceMock = {
isAuthenticated: function() {
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
}
};
spyOn(UserServiceMock, 'isAuthenticated');
在你的测试中你可以做到
it('should call isAuthenticated', function() {
expect(UserServiceMock.isAuthenticated).toHaveBeenCalled()
});