Categories
JavaScript Answers

How to mock import of JSON file with Jest?

Spread the love

Sometimes, we want to mock import of JSON file with Jest.

In this article, we’ll look at how to mock import of JSON file with Jest.

How to mock import of JSON file with Jest?

To mock import of JSON file with Jest, we can use jest.mock.

For instance, we write

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

to call 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.

Since a JSON file isn’t a JavaScript module, we need this option to mock it.

Conclusion

To mock import of JSON file with Jest, we can use jest.mock.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *