【问题标题】:Jasmine - How to spy on a function call within a function and again within a function on controller?Jasmine - 如何监视函数内的函数调用以及控制器上的函数内的函数调用?
【发布时间】:2016-12-19 07:27:13
【问题描述】:

我正在尝试为用咖啡脚本编写的 Angular 控制器编写单元测试,但我无法理解为什么有些测试通过了,即使它们不应该通过,以及为什么有些测试没有通过。

这是我的控制器:

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' 失败:

预期的 spy go 已使用 [ 'app.main.users.list' ] 调用,但是 它从未被调用过。

【问题讨论】:

    标签: javascript angularjs coffeescript jasmine


    【解决方案1】:

    我不熟悉 CoffeeScript 的语法,但在我看来,您在第一个函数中设置了错误的函数。试试这个:

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

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

    deferred.resolve();
    scope.$digest() // or scope.$apply()
    

    在您致电AddUserController.save() 之后。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多