4

Unit test vue component by mocking methods using vitest.

MyComponent.vue

<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>

I want to unit test method onVisibleChange by mocking onChange and check that onChange has been called.

MyComponent.spec.js

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!
})
0

1 Answer 1

1

It's not a good idea to test methods. Because the names of functions can be changed.

Better to test:

  1. Emits from component. Maybe your onChange() includes emit. This emit should be tested.
  2. Changes in templates. For example, your onChange() changes the template. So these changes should be tested too.
  3. Calls other functions. For example, you have common functions which you use in all your project. This functions can be spy.on
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.