Jest beforeAll vs beforeEach 意外行为

Jest beforeAll vs beforeEach unexpected behaviour

我有一个非常简单的测试,基本上我是在尝试模拟 i18next 的 t 函数:

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'));
});

changeDocumentTitle 实施:

import { t } from 'i18next';

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

很遗憾,测试失败。但是,如果我将它从 beforeAll 更改为 beforeEach,一切都很好。那个怎么样?为什么 beforeAll 不像 beforeEach 那样应用我的模拟?

提前致谢。

自 react-scripts v4 添加了默认的 jest 配置 resetMocks: truehttps://github.com/facebook/create-react-app/releases/tag/v4.0.0

这意味着在使用 beforeAll 运行测试之前将重置模拟。我建议保留 resetMocks: true,因为测试应该被隔离。