Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing react-intl components with enzyme

I have looked into react-intl for suggestions but it doesn't leave any explicit documentation for enzyme.

This is how I have been trying to write my tests.

import {IntlProvider} from 'react-intl';

const intlProvider = new IntlProvider({locale: 'en'}, {});
const intl = intlProvider.getChildContext();
const customMessage = shallow(<CustomMessage />, { options: { context: intl } });

But I keep getting the error

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

I looked into their repo and they seems to have made it work with 'react-addons-test-utils'.

Am I doing something wrong?

like image 949
Deadfish Avatar asked Apr 26 '16 13:04

Deadfish


People also ask

Should I use Enzyme for React testing?

Other times, Enzyme is better. If you want mimic real-world user interactions, the React Testing Library is the way to go because you can do the same with fireEvent functions. Meanwhile, Enzyme is better suited to situations where you have to match the state of React or some other function with state.

Can we use Enzyme and React testing library together?

A few days ago, React released version 18, which is not compatible with Enzyme. Furthermore, it probably is not achievable to use Enzyme with React 18. If you're still using Enzyme, it is time to look into alternatives. The most popular option besides Enzyme seems to be React Testing Library.

Which is better Enzyme or Jest?

Shallow rendering is one way that Enzyme keeps tests simpler than Jest. When you shallow-render a component with Enzyme, you render only that component. Enzyme doesn't render any of the children of that component. This is a useful restriction that ensures that you aren't testing too much in one test.


1 Answers

I've posted an answer to a similar question:

Injecting react-intl object into mounted Enzyme components for testing

You would be able to import { shallowWithIntl } from 'intl-helper' and then use shallowWithIntl() instead of Enzyme's shallow().

like image 63
Mirage Avatar answered Sep 17 '22 21:09

Mirage