在测试之间更改POJO模块的模拟实现



我试图模拟在测试中导入一个普通的旧Javascript对象,我希望每个测试有不同的实现。

如果我在文件的顶部mock,它会像预期的那样工作:

import { getConfig } from './'; // this contains the import config from 'configAlias';
jest.mock('configAlias', () => ({
hello: 'world',
}));
it('passes test', () => {
expect(getConfig()).toEqual({
hello: 'world,
});
});

但是我找不到doMock的任何组合,默认超过命名的导出,mockImplementation来获得以下工作:

import { getConfig } from './'; // this contains the import config from 'configAlias';

it('fails test1', () => {
jest.doMock('configAlias', () => ({
hello: 'world',
}));
const config = require('configAlias');
expect(getConfig()).toEqual({
hello: 'world,
});
});
it('fails test2', () => {
jest.doMock('configAlias', () => ({
hello: 'moon',
}));
const config = require('configAlias');
expect(getConfig()).toEqual({
hello: 'moon,
});
});

编辑1

基于@jonrsharpe,我尝试过

import { getConfig } from './'; // this contains the import config from 'configAlias';
const mockConfig = jest.fn();
jest.mock('configAlias', () => mockConfig);
it('fails test', () => {
mockConfig.mockImplementation({
hello: 'world',
});
expect(getSchema()).toEqual({ hello: 'world' });
});

解决了这个问题,诀窍是在单个测试中设置模拟之后导入/要求被测试的文件(而不是模拟的文件)。

beforeEach(() => {
jest.resetModules();
});
it('passes test 1', () => {
jest.mock('configAlias', () => ({
hello: 'world',
}));
const { getConfig } = require('getConfig');
expect(getConfig()).toEqual({
hello: 'world',
});
});
it('passes test 2', () => {
jest.mock('configAlias', () => ({
hello: 'moon',
}));
const { getConfig } = require('getConfig');
expect(getConfig()).toEqual({
hello: 'moon',
});
});

最新更新