3

I'm using the composition API in vue2, and trying to write a unit test that spys on a function to make sure another function has called it, but the test fails saying that my spy hasn't been called. Adding a console log in my actual component functions, I can see it is called as expected though. Codesandbox of the issue

Error:

Expected number of calls: >= 1
Received number of calls:    0

Component function:

export default defineComponent({
  name: 'PersonsReport',
  setup() {
    // other methods and vars

    const closeReportModal = (): void => {
      isReportModalOpen.value = false;
      resetSearchDates();
    };

    const resetSearchDates = () => {
      console.log('in resetSearchDates') // this fires in the test
    }

    return {
      closeReportModal,
      resetSearchDates
    }
  }
})

My test:

import Vue from 'vue';
import { mount } from '@vue/test-utils';
import CompositionApi from '@vue/composition-api';
import PersonsReport from '~/components/persons/PersonsReport.vue';

Vue.use(CompositionApi);

let wrapper: any;

const wrapperBeforeEach = () => {
  wrapper = mount(PersonsReport);
};

describe('PersonsReport', () => {
  beforeEach(async () => {
    wrapperBeforeEach();
  });

  test('closeReportModal to call resetSearchDates', async () => {
    const spy = jest.spyOn(wrapper.vm, 'resetSearchDates');
    await wrapper.vm.$nextTick();

    wrapper.vm.closeReportModal();
    await wrapper.vm.$nextTick();

    expect(spy).toHaveBeenCalled();

    spy.mockRestore();
  });
});
Sam Willis
  • 4,001
  • 7
  • 40
  • 59

1 Answers1

0

I think the issue is that you didn't call it inside the component you just expose it but function internal call inside setup object didn't count that way I guess. Perhaps const spy = jest.spyOn(wrapper.vm.closeReportModal, 'resetSearchDates'); would work or you should have something like that. Is there any chance we could produce it online?

stealhex
  • 1
  • 1
  • `const spy = jest.spyOn(wrapper.vm.closeReportModal, 'resetSearchDates');` produces the error that `Cannot spy the resetSearchDates property because it is not a function; undefined given instead` – Sam Willis Mar 10 '23 at 10:20
  • Here is a code sandbox that replicates the issue: https://codesandbox.io/s/vue-component-testing-with-jest-forked-ts4vmh?file=/src/tests/counter.spec.js – Sam Willis Mar 10 '23 at 10:49
  • Hello, I figure out how to do it. Here is the way how I did it https://codesandbox.io/s/vue-component-testing-with-jest-forked-2knmpu?file=/src/components/Counter.js, also there is the explanation of it https://stackoverflow.com/questions/72084274/vue3-using-vitest-tohavebeencalled-method. You can find why in the first answer – stealhex Mar 10 '23 at 19:27