Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest : Mock import of JSON file

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 ?

like image 778
Antoine Grandchamp Avatar asked Mar 23 '17 20:03

Antoine Grandchamp


People also ask

How do you mock a JSON object in Jest?

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.

How do you mock an import in Jest?

To mock an imported function with Jest we use the jest. mock() function. jest.

How do you mock data in 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.

How do you mock an NPM Jest module?

To mock a Node module with Jest, we can use the jest. createMockFromModule method. const utils = jest. createMockFromModule('../utils').


2 Answers

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 }) 
like image 80
Andreas Köberle Avatar answered Sep 22 '22 03:09

Andreas Köberle


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.

like image 25
spencer.sm Avatar answered Sep 23 '22 03:09

spencer.sm