How-to guide for unit testing Vue components and mocking methods using ViTest
P粉445750942
2023-08-29 00:23:20
<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>
Testing methods is not a good idea. Because the name of the function may change.
A better way is to test:
onChange()
contains the emission of the event. This issue should be tested.onChange()
changes the template. So these changes should also be tested.spy.on
.