簡體   English   中英

如何通過 Jest 測試 Vue 組件的計算 prop setter

[英]How to test a computed prop setter of Vue component by Jest

我想測試組件的設置器在嘗試分配無效值時是否拋出自定義錯誤。 我認為問題在於它甚至沒有調用 setter,它的行為就像它只是創建/分配給對象中的普通屬性一樣。 但它返回默認的 sortData。 謝謝您的幫助!

編輯:這里描述了帶有getter和setter的Vue組件道具,這正是我正在做的

組件中的代碼:

// 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...

你需要做sortPanel.setData({sort: 'anything'}) 您的二傳手將被正確調用。

setData 的文檔(來自 vue-test-utils)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM