I have a CRA-rewired typescript react app.
Jest is imported globally.
In order to use jest mocks I have to write
jest.mock('module-name')
ABOVE describe()
block and IN THE same file, e.g.
import { act, render, screen } from '@testing-library/react';
import { MyComponent } from './MyComponent';
import { something } from 'my-module';
jest.mock('my-module');
describe('MyComponent', () => {
afterAll(() => {
jest.unmock('my-module');
});
afterEach(() => {
jest.resetAllMocks();
jest.useRealTimers();
});
test('component renders', async () => {
(something as jest.MockedFunction<typeof something>).mockImplementation(() => 'banana');
const { container } = render(<MyComponent></MyComponent>);
expect(screen.queryByText('banana')).toBeVisible();
});
});
Now I have a few hundred test suites and thousands of tests.
Some of them have COMMON things I want to mock (like my-module
), but not ALL.
So I don’t want to use testSetup.js
to mock the modules in ALL tests, but I DO WANT to find a way to not have to write jest.mock()
over and over again.
So I tried creating a utilities module like so:
const TestUtilities = {
mockMyModule: () => {
jest.mock('my-module');
},
unmockMyModule: () => {
jest.unmock('my-module');
},
};
export default TestUtilities;
and then modified the original test:
import { act, render, screen } from '@testing-library/react';
import { MyComponent } from './MyComponent';
import { something } from 'my-module';
import TestUtilities from './TestUtilities';
TestUtilities.mockMyModule();
describe('MyComponent', () => {
afterAll(() => {
TestUtilities.unmockMyModule();
});
afterEach(() => {
jest.resetAllMocks();
jest.useRealTimers();
});
test('component renders', async () => {
(something as jest.MockedFunction<typeof something>).mockImplementation(() => 'banana');
const { container } = render(<MyComponent></MyComponent>);
expect(screen.queryByText('banana')).toBeVisible();
});
});
Unfortunately now test behaves as if my-module
is not mocked 🙁
Is there a way to re-use those jest.mock()
blocks?