如何通过Jest测试计算的Vue组件的prop setter

时间:2018-01-16 13:13:24

标签: javascript unit-testing vue.js jest

我想测试组件的setter是否在尝试分配无效值时抛出自定义错误。我认为问题是它甚至不会调用一个setter,它的行为就像它只是创建/分配给对象中的普通属性一样。但它返回默认的sortData。谢谢你的帮助!

修改:here is described Vue component prop with getters and setters, which is exactly what I'm doing

组件中的代码:

// Vue Component...
sort: {
  /**
   * Getter.
   * */
  get() {
    // Storing data from data().
    return this.sortData
  },

  /**
   * Setter.
   * */
  set(value) {
    if (value === 'none' || value === 'by-date' || value === 'by-ratings') {
      this.sortData = value
      this.$emit('sortChange', value)

    } else {
      // I want to test this error throwing.
      throw new EnumError('(Component::SortPanel): Sort property is of type Enum. ' +
        'It excepts either none, by-date or by-ratings values.')

    }
  }
},
// Vue Component...

测试用例:



beforeEach(function() {
  // Component for testing is inited by shallow function from vue-test-utils package.
  sortPanel = shallow(SortPanel)
})
// Other tests...
it('should have property sort', function() {
  expect(sortPanel.vm.sort).toBe('none')

  // Should be either none, by-date or by-ratings.
  expect(() => {
    sortPanel.vm.sort = 'anything'
  }).toThrow(EnumError)
})
// Other tests...




1 个答案:

答案 0 :(得分:0)

您需要sortPanel.setData({sort: 'anything'})。你的二传手将被正确调用。

Documentation for setData(来自vue-test-utils)