Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manual mock React-Intl with Jest to have snapshot testing

I have been struggling mocking React-Intl library with Jest because I'm having this error when I run tests:

Invariant Violation: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.

The documentation of this library says that we have to create a folder in root project called __Mocks__ and then add this file:

// ./__mocks__/react-intl.js
import React from 'react';
const Intl = require.requireActual('react-intl');

// Here goes intl context injected into component, feel free to extend
const intl = {
  formatMessage: ({defaultMessage}) => defaultMessage
};

Intl.injectIntl = (Node) => (props) => <Node {...props} intl={intl}/>;

module.exports = Intl;

But nothing happens.

like image 818
Albert Olivé Avatar asked May 03 '17 13:05

Albert Olivé


People also ask

How do you write a snapshot test in React?

When writing snapshot tests for a React component, you first need to have code in a working state. Then, generate a snapshot of its expected output given certain data. The snapshot tests are committed alongside the component. Jest, a testing framework, will compare the snapshot to the rendered output for the test.

Is snapshot testing is supported in Jest?

Jest has been rewritten with performance in mind, and snapshot testing is not an exception. Since snapshots are stored within text files, this way of testing is fast and reliable. Jest generates a new file for each test file that invokes the toMatchSnapshot matcher.

How do I create a snapshot in Jest?

toMatchSnapshot() creates a snapshot if it does not exist, saves it, and checks if a snapshot is consistent with previous stored snapshots. If there is an existing snapshot, Jest compares the two snapshots. If they match, the test passes. Snapshots that do not match cause the test to fail.

Does React testing library have snapshot?

Snapshot testing It works well with React components because when you render a component you can view the DOM output and create a “snapshot” at the time of run.


1 Answers

After hours looking in it, I found that what I needed to change was the way I was requiring react-intl package. So, I changed that line:

const Intl = require.requireActual('react-intl');

to that:

const Intl = jest.genMockFromModule('react-intl');

So the final file looks like this:

import React from 'react';
const Intl = jest.genMockFromModule('react-intl'); // <-- This is the change

const intl = {
  formatMessage: ({defaultMessage}) => defaultMessage
};

Intl.injectIntl = (Node) => (props) => <Node {...props} intl={intl}/>;

module.exports = Intl;

Hope this helps!

like image 65
Albert Olivé Avatar answered Nov 04 '22 09:11

Albert Olivé