Jest : Mock import of JSON file
You can either use moduleNameMapper
in your jest settings to point the import to an mocked json file.
{
"moduleNameMapper": {
"setting.json": "<rootDir>/__mocks__/setting.json"
}
}
Or you can use jest.mock
inside your test to mock the file directly, note that you have to add the { virtual: true }
parameter.
jest.mock('path/to/setting.json', ()=>({
settings: 'someSetting'
}), { virtual: true })
For those looking to mock JSON in the form of an Array
, just return an array from the callback.
jest.mock('./data.json', () => ([1, 2, 3]));
You can return other valid JSON types as well: Object
, String
, Number
, Boolean
, or Null
.