6
'use strict'

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

    $scope.init()
]

から呼び出されたspyOn場合のテストを書きたいと思います。私の には、次のものがあります。isAuthenticatedUserServicebeforeEach

  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 が呼び出されたときに、変数を true に設定するだけです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 に答える