2014-08-27 45 views
6
'use strict' 

webApp.controller 'NavigationController', [ 
    '$scope' 
    '$rootScope' 
    'UserService' 
    ($scope, $rootScope, UserService) -> 
    $scope.init = -> 
     UserService.isAuthenticated().then (authenticated) -> 
     $scope.isAuthenticated = authenticated 

    $scope.init() 
] 

我想写一个测试spyOn如果isAuthenticatedUserService被调用。在我beforeEach,我有:我该如何窥探模拟服务AngularJS/Karma?

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 

任何帮助,将不胜感激..谢谢

回答

5

您可以只设置一个变量设置为true时isAuthenticated叫你UserServiceMock。例如:

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() 
}); 
+0

这个假设'UserServiceMock'可用于测试的范围,是吗? – Shamoon 2014-08-27 18:46:59

+1

是的,你需要声明它作为beforeEach之外的变量 – rob 2014-08-27 18:55:19