Jest: Importing a JSON file

I am currently testing one of my React components like this:

it('renders correctly', () => {
  const tree = renderer.create(<Scene {...props} />).toJSON();
  expect(tree).toMatchSnapshot();
});

      

My component is Scene

importing a file setting.json

. I have this file in my local instance, but I am not pushing it to the CI instance. So when he tries to import it, the file was not found.

Is there a way to mock this file in my test?

+3


source to share


1 answer


You can use moduleNameMapper

jest in the preferences to specify import to the manufactured 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 need to add a parameter { virtual: true }

.

jest.mock('path/to/setting.json', ()=>({
  settings: 'someSetting'
}), { virtual: true })

      

+5


source







All Articles