Yauheni
Yauheni

Reputation: 33

Jest beforeAll vs beforeEach unexpected behaviour

I have a quite simple test, basically I'm trying to mock i18next's t function:

import { t } from 'i18next';
import { changeDocumentTitle } from './utils';

jest.mock('i18next');

const tMock = (key: string): string => key;

beforeAll(() => {
  (t as jest.Mock).mockImplementation(tMock);
});

test('test changeDocumentTitle function', () => {
  changeDocumentTitle('string');
  expect(document.title).toEqual(tMock('string'));
});

and the changeDocumentTitle implementation:

import { t } from 'i18next';

export const changeDocumentTitle = (titleKey: string): void => {
  document.title = t(`${titleKey}`);
};

Unfortunately, the test fails. But if I change it from beforeAll to beforeEach, everything's fine. How is that? Why beforeAll is not applying my mock unlike beforeEach?

Thanks in advance.

Upvotes: 2

Views: 1288

Answers (1)

Julian Flynn
Julian Flynn

Reputation: 328

Since react-scripts v4 it added the default jest config resetMocks: true: https://github.com/facebook/create-react-app/releases/tag/v4.0.0

This means that the mocks are being reset before the tests runs with beforeAll. I recommended keeping resetMocks: true, because tests should be isolated.

Upvotes: 2

Related Questions