首页  >  问答  >  正文

使用ViTest对Vue组件进行单元测试并模拟方法的方法指南

<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粉445750942P粉445750942417 天前533

全部回复(1)我来回复

  • P粉311423594

    P粉3114235942023-08-29 12:51:44

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

    更好的方法是测试:

    1. 从组件中发出的事件。也许你的 onChange() 包含了事件的发出。这个发出应该被测试。
    2. 模板中的变化。例如,你的 onChange() 改变了模板。所以这些变化也应该被测试。
    3. 调用其他函数。例如,你有一些在项目中通用的函数。这些函数可以使用 spy.on 进行测试。

    回复
    0
  • 取消回复