Jest : Mock import of JSON file

2020-06-06 20:35发布

问题:

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 ?

回答1:

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 })


回答2:

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.