角度测试 - 触发变更无法正常工作

时间:2017-03-15 14:49:44

标签: javascript angularjs unit-testing mocha chai

我有一个指令,我正在尝试进行单元测试,其中包括一个'更改'事件:

iElement.on 'change', (evt) ->
          scope.$apply () ->
            scope.model.user.data.roles = iElement.val()

这是我的主要测试代码,它初始化scope.model,然后尝试更改它。

it 'modifies the existing role - INCOMPLETE', () ->
      scope.model = user: data: roles: Object.keys user.data.roles
      scope.$broadcast 'event:gotUser'
      scope.model.user.data.roles = ['Pizza']
      scope.$digest()
      element.triggerHandler('change')
      console.log(element.text())

不幸的是,'change'事件没有被触发,指令返回的值是旧的:'Delicious×Delicious'

更新

固定指令:

compiled = $compile '<div <select heli-tag-control multiple="" style="width : 100%;"> </select></div>'

compiled = $compile '<div heli-tag-control multiple="" style="width : 100%;"> </div>'

更新了测试:

it 'modifies the existing role - INCOMPLETE', () ->
      scope.model = user: data: roles: Object.keys user.data.roles
      scope.$broadcast 'event:gotUser'
      scope.model = user: data: roles: ['Happy', 'Banana']
      element.val(scope.model.user.data.roles).triggerHandler('change')
      expect(element.text()).to.contain 'Banana'

1 个答案:

答案 0 :(得分:0)

事实证明我只需要再次播放我的'gotUser'事件,然后传播更改。

完成测试:

it 'modifies the existing role - INCOMPLETE', () ->
      scope.model = user: data: roles: Object.keys user.data.roles
      scope.$broadcast 'event:gotUser'
      scope.model = user: data: roles: ['Happy', 'Banana']
      element.val(scope.model.user.data.roles).triggerHandler('change')
      scope.$broadcast 'event:gotUser'
      expect(element.text()).to.contain 'Banana'