How to use different mocks for each test with vi.mock? #3589
-
Hello, I’m having trouble using different mocks for each test in my test suite. import { render, screen } from '@testing-library/react';
import { vi } from 'vitest';
import HomePage from '../app/page';
describe('Homepage', () => {
test('Home page renders correctly', async () => {
render(await HomePage());
expect(screen.getByText('get started')).toBeInTheDocument();
});
test('Conditional rendering when authenticated', async () => {
vi.mock('@clerk/nextjs', () => {
return {
auth: () => new Promise((resolve) => resolve({ userId: 'fefsfehrf' })),
ClerkProvider: ({ children }) => <div>{children}</div>,
useUser: () => ({
isSignedIn: true,
user: {
id: 'user_8JkL2mP0zX6d8JkL2mP0zX6dJ',
fullName: 'Thrall Durotan',
},
}),
};
});
const { debug } = render(await HomePage());
debug();
const link = screen.getByRole('link');
expect(link).toHaveAttribute('href', '/journal');
});
test('Conditional rendering when not authenticated', async () => {
vi.mock('@clerk/nextjs', () => {
return {
auth: () => new Promise((resolve) => resolve({ userId: null })),
ClerkProvider: ({ children }) => <div>{children}</div>,
useUser: () => ({
isSignedIn: false,
user: null,
}),
};
});
const { debug } = render(await HomePage());
debug();
const link = screen.getByRole('link');
expect(link).toHaveAttribute('href', '/new-user');
});
});
I’m calling vi.mock twice, once in the second test and once in the third test. However, it seems that the second call to vi.mock is overwriting the first mock as when I console log userId both tests use it mocked as null, which means both tests are using the mock defined in the second call. I’ve tried calling vi.resetAllMocks in an afterEach block and setting mockReset: true in my config, but it's not really problem of a mock reset rather some overwrite problem. Can you help me understand how to use different mocks for each test with vi.mock? Is there something I’m missing or doing wrong? Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
https://vitest.dev/api/vi.html#vi-mock
|
Beta Was this translation helpful? Give feedback.
-
What if you don't have a named export, eg. a vue component: |
Beta Was this translation helpful? Give feedback.
You can pass down variables with
vi.hoisted
and change the implementation before running a test: