Jasmine - 如何监视函数内的函数调用以及控制器上的函数内部?

时间:2016-08-12 10:05:33

标签: javascript angularjs coffeescript jasmine

我正在尝试编写用咖啡脚本编写的角度控制器的单元测试,我有理解为什么有些测试正在通过,即使它们不应该,为什么有些不是。

这是我的控制者:

add_user_controller.coffee

(->
class AddUserController
  @$inject = ['$scope', '$http', '$state', 'OfficesService', 'UserFactory']

  constructor: (@$scope, @$http, @$state, @OfficesService, UserFactory) ->
    @offices = @OfficesService
    @user = new UserFactory()

  save: ->
    self = this

    @user.save().then ->
      self.$state.go('app.main.users.list')

angular
  .module('app')
  .controller('AddUserController', AddUserController)
)()

这些是我的测试:

add_user_controller.test.coffee

'use strict'

describe 'Controller: AddUserController', ->
    AddUserController = null
    scope = {}
    http = {};
    state = {
      go: (value) ->
        bar = value
    }
    OfficesService = {};
    UserFactory = null
    q = null

  # Initialize the controller and scope
  beforeEach ->
    # Load the main module
    module 'app'

    inject ($rootScope, $controller, _UserFactory_, $q) ->
      UserFactory = _UserFactory_
      q = $q
      scope = $rootScope.$new
      AddUserController = $controller 'AddUserController',
        $scope: scope,
        $http: http,
        $state: state,
        OfficesService: OfficesService,
        UserFactory: UserFactory

  it 'should call "save" on "user"', ->
    deferred = q.defer()
    spyOn(AddUserController.user, "save").and.returnValue deferred.promise
    AddUserController.save()
    expect(AddUserController.user.save).toHaveBeenCalled

  it 'should move to the "app.main.users.list" after "save" method has been called', ->
    spyOn(AddUserController.$state, "go")
    AddUserController.save()
    expect(AddUserController.$state.go).toHaveBeenCalledWith('app.main.users.list')

第一个问题

即使我在控制器中注释以下行,测试'should call "save" on "user"'也在传递:

#    @user.save().then ->
#       self.$state.go('app.main.users.list')

第二个问题

测试'should move to the "app.main.users.list" after "save" method has been called'失败了:

  

预期的间谍去了['app.main.users.list'],但是   它从未被称为。

1 个答案:

答案 0 :(得分:0)

我不熟悉CoffeeScript的语法,但它对我来说是你在第一个中设置你的间谍错误的功能。试试这个:

spyOn(UserFactory, "save").and.returnValue deferred.promise 

对于第二个,我认为$state的间谍设置​​正确但您需要在等待返回承诺时触发摘要周期。如果是我,我会将UserFactory.save()和你的延迟变量的间谍移到beforeEach()。然后在两个测试中尝试添加

deferred.resolve();
scope.$digest() // or scope.$apply()
致电AddUserController.save()

。希望这有用。