使用ViTest对Vue组件进行单元测试并模拟方法的方法指南
P粉445750942
P粉445750942 2023-08-29 00:23:20
0
1
538
<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>
P粉445750942
P粉445750942

全部回复(1)
P粉311423594

测试方法并不是一个好主意。因为函数的名称可能会改变。

更好的方法是测试:

  1. 从组件中发出的事件。也许你的 onChange() 包含了事件的发出。这个发出应该被测试。
  2. 模板中的变化。例如,你的 onChange() 改变了模板。所以这些变化也应该被测试。
  3. 调用其他函数。例如,你有一些在项目中通用的函数。这些函数可以使用 spy.on 进行测试。
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!