iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 7
1
Modern Web

Vue 怎麼寫測試系列 第 7

Day 7. 平安夜,就是要射點東西

  • 分享至 

  • twitterImage
  •  

對,就是射出事件啦 (Emit Event)

當然是靠官方提供的 helper function

我們先偷看 Vue 的實作,等等再來看測試。

假設,今天要來實作一個優惠券的驗證功能
驗證完後,我們會廣播一個 applied 的事件。

export default {
    // ... Vue 的其他設定
    
    methods: {
      validate (code) {
        this.valid = this.coupons.includes(code)
        
        // 講射出太難懂了,果然還是要說這叫:廣播 (broadcast)
        if( this.valid )
            this.$emit('applied');
      }
    }
}

這個時候來看我們的測試,

it ('優惠券存在的話,要廣播 applied。', () => {
    let wrapper = mount(CouponCode)
    
    // 設定假的資料
    wrapper.setData({
        coupons: ['50OFF']
    })
    
    // 手動觸發驗證
    wrapper.vm.validate('50OFF')
    
    // 這裡就是關鍵
    expect(wrapper.emitted().applied).toBeTruthy()
})

如果我們在測試裡面用 console.log( wrapper.emitted() )
來查看資料的話,你會發現 applied 是一個雙層的 array


  { applied: [ [] ] }

不知道為什麼結果長這樣嗎?
我多列幾種結果讓你觀察,應該就看得懂了吧。

  this.$emit('applied')
  wrapper.emitted() // => { applied: [ [] ] }
  
  this.$emit('applied', '123')
  wrapper.emitted() // => { applied: [ [123] ] }

  this.$emit('applied')
  this.$emit('applied', '123')
  wrapper.emitted() // => { applied: [ [], [123] ] }  

OK, 了解這些之後,我們就可以寫測試來確認事件有沒有被觸發囉。


上一篇
Day 6. 是條狀的都行,管它香蕉還芭蕉
下一篇
Day 8. 工具人的工具箱建置
系列文
Vue 怎麼寫測試30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言