I'm trying to test if a composable's method is called from my store. Here's what I have:
/stores/ui
:
import { defineStore } from 'pinia';
import { useUtils } from '@/composables/utils';
const { sendEvent } = useUtils();
interface State {
tab: string,
}
export const useUIStore = defineStore('ui', {
state: (): State => ({
tab: 'Home',
}),
actions: {
setTab(tabName: string) {
this.tab = tabName;
sendEvent('navigation', `click_${tabName}`);
},
}
})
@/composables/utils
:
export function useUtils() {
const sendEvent = (name: string, value: string) => {
// do stuff
};
return {
sendEvent
};
}
And here's my test file:
import { setActivePinia, createPinia } from 'pinia'
import { useUIStore } from '@/stores/ui';
import { useUtils } from '@/composables/utils';
describe('', () => {
let uiStore;
beforeEach(() => {
setActivePinia(createPinia());
uiStore = useUIStore();
})
it('Sets the active tab', () => {
let sendEvent = jest.spyOn(useUtils(), 'sendEvent');
expect(uiStore.tab).toBe('Home');
uiStore.setTab('help');
expect(uiStore.tab).toBe('help');
expect(sendEvent).toHaveBeenCalledTimes(1);
});
})
I've also tried mocking the import:
jest.mock(
'@/composables/utils',
() => {
function useUtils() {
return {
sendEvent: jest.fn(),
}
}
return {
useUtils
};
},
{ virtual: true },
);
import { useUtils } from '@/composables/utils';
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1 Received number of calls: 0
What's the correct way of adding a spy to sendEvent
?
CodePudding user response:
In your test file - mock the utils:
const mockSendEvent = jest.fn();
jest.mock("@/composables/utils", () => ({
useUtils: () => ({
sendEvent: mockSendEvent,
}),
}));
and then update your test to use the mock:
it('Sets the active tab', () => {
expect(uiStore.tab).toBe('Home');
uiStore.setTab('help');
expect(uiStore.tab).toBe('help');
expect(mockSendEvent).toHaveBeenCalledTimes(1);
});