使用ViTest對Vue元件進行單元測試並模擬方法的方法指南
P粉445750942
P粉445750942 2023-08-29 00:23:20
0
1
539
<p>使用vitest來模擬方法,透過單元測試vue組件。 </p> <p><em>MyComponent.vue</em></p> <pre class="brush:php;toolbar:false;"><script setup> import { ref } from "vue"; const isSelectAll = ref(true); const selectAllModel = ref(false); const onChange = () => { isSelectAll.value = true; selectAllModel.value = false; }; const onVisibleChange = () => { // do something than call onChange(); }; </script></pre> <p>我想透過模擬<code>onChange</code>來單元測試<code>onVisibleChange</code>方法,並檢查<code>onChange</code>是否被呼叫。 </p> <p><em>MyComponent.spec.js</em></p> <pre class="brush:php;toolbar:false;">import { mount } 從 'vitest'; import { ref } 從 'vue'; import MyComponent from './MyComponent.vue'; describe('MyComponent', () => { const wrapper = shallowMount(MyComponent); const spy = vi.spyOn(wrapper.vm, 'onChange'); wrapper.vm.onVisibleChange(); expect(spy).toHaveBeenCalled(); expect(wrapper.vm.onChange).toHaveBeenCalled(); // Both the expect gives error: AssertionError: expected "onChange" to be called at least once //Also tried const mock = vi.fn(); wrapper.vm.onChange = mock; wrapper.vm.onVisibleChange(); expect(mock).toHaveBeenCalled(); // AssertionError: expected "spy" to be called at least once expect(wrapper.vm.onChange).toHaveBeenCalled(); // TypeError: [Function onChange] is not a spy or a call to a spy! })</pre></p>
P粉445750942
P粉445750942

全部回覆(1)
P粉311423594

測試方法並不是一個好主意。因為函數的名稱可能會改變。

更好的方法是測試:

  1. 從元件中發出的事件。也許你的 onChange() 包含了事件的發出。這個發出應該要被測試。
  2. 模板中的變化。例如,你的 onChange() 改變了模板。所以這些變化也應該要被測試。
  3. 呼叫其他函數。例如,你有一些在專案中通用的函數。這些函數可以使用 spy.on 進行測試。
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!