[英]How to test CSS Framework custom components with vue-test-utils
[英]vue-test-utils - how to handle $refs?
情況
我正在嘗試對組件進行shallowMount
安裝,但未成功。
該組件使用$refs
來讀取div
的高度。 該值在計算屬性中讀取。 然后在mounted
的生命周期中,我將該值保存在商店中。
邏輯本身很簡單並且工作正常。 但是在測試套件中,組件的安裝中斷,因為$refs
鍵是undefined
。
明確一點:我不打算測試$refs
,我只需要安裝組件並繼續進行實際的單元測試。
組件
這是標記:
<div ref="tgmp">
我將 div 的高度保存在計算屬性中:
computed: {
barH() {
return this.$refs.tgmp.clientHeight
}
}
然后,在掛載的生命周期中,我提交存儲中的值:
this.$store.commit('setBarHeight', this.barH)
考試
這是測試。 我省略了不相關的東西,比如在 localVue 中安裝商店。
beforeEach(() => {
wrapper = shallowMount(Bar, {
store,
})
})
test('is a Vue instance', () => {
expect(wrapper.isVueInstance()).toBeTruthy()
})
錯誤
Error in mounted hook: "TypeError: Cannot read property 'clientHeight' of undefined"
試圖
我一直在嘗試在任何地方尋找解決方案,但找不到。 我試圖模擬 $refs,但沒有成功:
wrapper = shallowMount(ThePlayerBar, {
store,
mocks: {
$refs: {
tgmp: {
clientHeight: 600
}
}
}
})
問題
如何在mounted
的生命周期中掛載使我們使用$refs
的組件?
shallowMount
應該提供 refs,所以this.$refs.tgmp
應該是<div>
元素,以防<div ref="tgmp">
存在於初始渲染的視圖中。
$refs
不應該被嘲笑,因為它是內部屬性並在組件初始化時分配。 它是依賴於 ref 的計算屬性,因此可以在必要時對其進行模擬,因為在 JSDOM 中元素高度應為 0:
jest.spyOn(ThePlayerBar.options.computed, 'barH').mockReturnValue(600);
或者:
wrapper = shallowMount(Bar, {
store,
computed: { barH: () => 600 }
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.