I am migrating from Jest to Vitest and found out that most of my spyOn methods aren't working because they are declared outside of the test scope:
const notificationSpy = vi.spyOn(NotificationActions, 'addNotification');
describe('PostboxList', () => {
const renderComponent = (store: Store) => {
render(<PostboxList />, {
store,
});
};
it('the notification is visible when fetching status is HasError', async () => {
const store = mockStore({
postbox: {
documents: {
data: [],
fetchingStatus: DataFetchingStatus.HasError,
},
messages: {
data: [],
fetchingStatus: DataFetchingStatus.HasError,
},
},
});
renderComponent(store);
expect(notificationSpy).toHaveBeenCalledOnce({
title: 'POSTBOX.ERROR.TITLE',
text: 'POSTBOX.ERROR.TEXT',
});
});
});
Now if I move the declaration of my spyOn method to inside the test scope, the test will pass:
describe('PostboxList', () => {
const renderComponent = (store: Store) => {
render(<PostboxList />, {
store,
});
};
it('the notification is visible when fetching status is HasError', async () => {
const notificationSpy = vi.spyOn(NotificationActions, 'addNotification');
const store = mockStore({
postbox: {
documents: {
data: [],
fetchingStatus: DataFetchingStatus.HasError,
},
messages: {
data: [],
fetchingStatus: DataFetchingStatus.HasError,
},
},
});
renderComponent(store);
expect(notificationSpy).toHaveBeenCalledOnce({
title: 'POSTBOX.ERROR.TITLE',
text: 'POSTBOX.ERROR.TEXT',
});
});
});
My test config inside Vite config:
test: {
globals: true,
environment: 'jsdom',
setupFiles: './vitest.setup.ts',
include: ['**/*.{test, spec}.{ts,tsx,js,jsx}'],
exclude: [...configDefaults.exclude, 'plop', './vitest.setup.ts'],
deps: {
inline: ['vitest-canvas-mock'],
},
testTimeout: 10000,
threads: false,
alias: tsconfigPaths(),
mockReset: true,
restoreMocks: true,
clearMocks: true,
css: true,
}
I already tried resetting the mock and the spyOn on beforeEach and afterEach but had no success.
I've researched already but no answers or similar issues were found.
Removing these configs solved the issue:
threads: false,
mockReset: true,
restoreMocks: true,
clearMocks: true,