I am trying to mock the import of a Plain Old Javascript Object in a test, where I want different implementations for each test.
If I mock at the top of the file it works as expected:
JavaScript
x
12
12
1
import { getConfig } from './'; // this contains the import config from 'configAlias';
2
3
jest.mock('configAlias', () => ({
4
hello: 'world',
5
}));
6
7
it('passes test', () => {
8
expect(getConfig()).toEqual({
9
hello: 'world,
10
});
11
});
12
But I cannot find any combination of doMock, default over named exports, mockImplementation to get the following to work:
JavaScript
1
25
25
1
import { getConfig } from './'; // this contains the import config from 'configAlias';
2
3
4
it('fails test1', () => {
5
jest.doMock('configAlias', () => ({
6
hello: 'world',
7
}));
8
const config = require('configAlias');
9
10
expect(getConfig()).toEqual({
11
hello: 'world,
12
});
13
});
14
15
it('fails test2', () => {
16
jest.doMock('configAlias', () => ({
17
hello: 'moon',
18
}));
19
const config = require('configAlias');
20
21
expect(getConfig()).toEqual({
22
hello: 'moon,
23
});
24
});
25
Edit 1
Based on @jonrsharpe I have tried
JavaScript
1
12
12
1
import { getConfig } from './'; // this contains the import config from 'configAlias';
2
3
const mockConfig = jest.fn();
4
jest.mock('configAlias', () => mockConfig);
5
6
it('fails test', () => {
7
mockConfig.mockImplementation({
8
hello: 'world',
9
});
10
expect(getSchema()).toEqual({ hello: 'world' });
11
});
12
Advertisement
Answer
Worked it out, the trick is to import/require the file under test (not the mocked file) AFTER setting the mock in the individual test. No import at the top of the file.
JavaScript
1
26
26
1
beforeEach(() => {
2
jest.resetModules();
3
});
4
5
it('passes test 1', () => {
6
jest.mock('configAlias', () => ({
7
hello: 'world',
8
}));
9
const { getConfig } = require('getConfig');
10
11
expect(getConfig()).toEqual({
12
hello: 'world',
13
});
14
});
15
16
it('passes test 2', () => {
17
jest.mock('configAlias', () => ({
18
hello: 'moon',
19
}));
20
const { getConfig } = require('getConfig');
21
22
expect(getConfig()).toEqual({
23
hello: 'moon',
24
});
25
});
26