How-to guide for unit testing Vue components and mocking methods using ViTest
P粉445750942
P粉445750942 2023-08-29 00:23:20
0
1
572
<p>Use vitest to simulate methods and unit test vue components. </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>I want to unit test the <code>onVisibleChange</code> method by mocking <code>onChange</code> and check if <code>onChange</code> is called. </p> <p><em>MyComponent.spec.js</em></p> <pre class="brush:php;toolbar:false;">import { mount } from 'vitest'; import { ref } from '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

reply all(1)
P粉311423594

Testing methods is not a good idea. Because the name of the function may change.

A better way is to test:

  1. Events emitted from the component. Maybe your onChange() contains the emission of the event. This issue should be tested.
  2. Changes in templates. For example, your onChange() changes the template. So these changes should also be tested.
  3. Call other functions. For example, you have some functions that are common across projects. These functions can be tested using spy.on.
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template