You can use jest.doMock(moduleName, factory, options) to mock the config.json file and its content.
E.g.
index.jsx:
import React from 'react';
import * as configData from './config.json';
console.log('configData: ', configData);
export default function ComponentElement() {
return <div>{configData.isFlag ? 'ArrowForwardIosIcon' : 'others'}</div>;
}
config.json:
{
"isFlag": false
}
index.test.jsx:
import { shallow } from 'enzyme';
import React from 'react';
describe('68768758', () => {
let ComponentElement;
beforeEach(() => {
jest.resetModules();
});
test('should render others', () => {
ComponentElement = require('.').default;
const wrapper = shallow(<ComponentElement />);
expect(wrapper).toMatchInlineSnapshot(`
<div>
others
</div>
`);
});
test('should render icon', () => {
jest.doMock('./config.json', () => ({ isFlag: true }));
ComponentElement = require('.').default;
const wrapper = shallow(<ComponentElement />);
expect(wrapper).toMatchInlineSnapshot(`
<div>
ArrowForwardIosIcon
</div>
`);
});
});
test result:
PASS examples/68768758/index.test.jsx (9.092 s)
68768758
✓ should render others (25 ms)
✓ should render icon (13 ms)
› 1 snapshot written.
console.log
configData: { isFlag: [Getter], default: { isFlag: false } }
at Object.<anonymous> (examples/68768758/index.js:3:9)
console.log
configData: { isFlag: [Getter], default: { isFlag: true } }
at Object.<anonymous> (examples/68768758/index.js:3:9)
Snapshot Summary
› 1 snapshot written from 1 test suite.
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 1 written, 1 passed, 2 total
Time: 10.24 s
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'enzyme',
setupFilesAfterEnv: [
'jest-enzyme'
],
setupFiles: ['./jest.setup.js'],
testEnvironmentOptions: {
enzymeAdapter: 'react16',
},
};
package versions:
"jest": "^26.6.3",
"ts-jest": "^26.4.4",
"jest-enzyme": "^7.1.2",