我试图在测试中模拟普通旧 Javascript 对象的导入,我希望每个测试都有不同的实现。
如果我在文件顶部模拟它按预期工作:
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',
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句