With React 17 update, it is not necessary to include import React from 'react'; explicitly in React components anymore. We would like to take advantage from the feature, so we have removed all the React imports from our source code.
This however breaks the jest snapshot tests that we are using for the app which triggers an error:
ReferenceError: React is not defined
I was wondering if there are any workarounds for this issue.
Here is an example jest snapshot test we are using:
import { Provider } from 'react-redux';
import renderer from 'react-test-renderer';
import { applyMiddleware, createStore } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import { Price } from '../../../app/components/common/Price';
import rootReducer from '../../../app/ducks/rootReducer';
const epicMiddleware = createEpicMiddleware();
const store = createStore(
rootReducer, applyMiddleware(epicMiddleware)
);
const price = 100;
describe('<Price> Component test', () => {
it('should match snapshot', () => {
const tree = renderer.create(
<Provider store={store}>
<Price price={price} currencyKey="€">{price}</Price>
</Provider>
);
expect(tree).toMatchSnapshot();
});
});
and it's main component:
import { useSelector } from 'react-redux';
import Text from 'app/components/common/Text';
import { CurrencyFormatter } from 'app/services/common/js-price-formatter';
export const Price = ({ style, price, currencyKey }) => {
const country = useSelector(state => state.locale.get('country'));
const currencyFormatter = CurrencyFormatter.forCountry(country);
return <Text style={style} label={currencyFormatter.format(price, currencyKey)} />;
};
export default Price;
Here is an extract of package.json
{
"dependencies": {
"react": "17.0.2",
...
},
"devDependencies": {
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"jest-circus": "^26.6.3",
"react-dom": "17.0.2",
"react-test-renderer": "17.0.2",
...
},
}