search

Home  >  Q&A  >  body text

How-to guide for unit testing Vue components and mocking methods using ViTest

<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粉445750942P粉445750942457 days ago573

reply all(1)I'll reply

  • P粉311423594

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

    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.

    reply
    0
  • Cancelreply