I am trying to test a nuxt page with vitest.
It has a child component toolbar which emits an event “on-filters-change”. When this event is triggered, the page calls a method “onFilter”. My test should verify this method is well called when the event happens:
describe('Test filtering', () => {
let toolbar: Awaited<ReturnType<typeof wrapper.find>>;
beforeAll(() => {
toolbar = wrapper.findComponent('[data-unit="toolbar"]');
});
it('Should find the toolbar', async () => {
expect(toolbar).toBeTruthy();
});
describe('First filter', () => {
it('Should listen to the toolbar events', async () => {
const spy = vi.spyOn(wrapper.vm, 'onFilter');
// wrapper.vm.onFilter({ ... });
await toolbar.vm.$emit('on-filters-change', { ... });
expect(toolbar.emitted()['on-filters-change']).toBeTruthy(); // Ok
expect(spy).toHaveBeenCalled(); // NOK
spy.mockRestore();
});
});
});
If I call myself the method “onFilter” (commented line), the test passes. I suppose this is due to an event detection issue ?
Or can the “onFilter” method being called after I looked if the spy has been called ?
I guess it is a common purpose so I am looking forward to master this test case … Thanks for your help