6
'use strict'

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

    $scope.init()
]

我想写一个测试spyOnifisAuthenticated被调用 from 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

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

4

1 回答 1

5

当 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()
});
于 2014-08-27T14:06:47.590 回答