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

问题描述 投票:1回答:1

我想测试组件的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...
javascript unit-testing vue.js jest
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.