I am currently testing one of my React component like this:
it('renders correctly', () => { const tree = renderer.create(<Scene {...props} />).toJSON(); expect(tree).toMatchSnapshot(); });
My component Scene
imports a setting.json
file. I have that file on my local instance, but I do not push it on my CI instance. So when it tries to import it, the file is not found.
Is there a way to mock this file in my test ?
mock to mock the path/to/setting. json JSON file. We pass in a function that returns the JSON object as the 2nd argument and an object with the virtual property set to true to let us mock the JSON file. virtual set to true lets us mock modules that don't exist anywhere in the system.
To mock an imported function with Jest we use the jest. mock() function. jest.
In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.
To mock a Node module with Jest, we can use the jest. createMockFromModule method. const utils = jest. createMockFromModule('../utils').
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With