使用ViTest对Vue组件进行单元测试并模拟方法的方法指南
P粉445750942
2023-08-29 00:23:20
<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 } 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>
测试方法并不是一个好主意。因为函数的名称可能会改变。
更好的方法是测试:
onChange()
包含了事件的发出。这个发出应该被测试。onChange()
改变了模板。所以这些变化也应该被测试。spy.on
进行测试。