Skip to content

Instantly share code, notes, and snippets.

@natterstefan
Created June 4, 2018 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natterstefan/cb4466c48e927b2d064332308b7afc53 to your computer and use it in GitHub Desktop.
Save natterstefan/cb4466c48e927b2d064332308b7afc53 to your computer and use it in GitHub Desktop.
Jest Helper for react-intl
/**
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*
* Docs
* - https://github.com/yahoo/react-intl/wiki/Testing-with-React-Intl#enzyme
* - https://github.com/yahoo/react-intl/wiki/Testing-with-React-Intl#snapshot-testing
*
* Other articles
* - test other languages: https://gist.github.com/mirague/c05f4da0d781a9b339b501f1d5d33c37/#gistcomment-232527
* - modify intl in tests: https://blog.theodo.fr/2017/12/clean-tests-react-intl-missing-message-errors-console/
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import renderer from 'react-test-renderer'; // eslint-disable-line import/no-extraneous-dependencies
import { mount, shallow } from 'enzyme'; // eslint-disable-line import/no-extraneous-dependencies
// You can pass your messages to the IntlProvider. Optional: remove if unneeded.
import { getMessages } from '../../../config/languages';
// Create the IntlProvider to retrieve context for wrapping around.
const intlProvider = new IntlProvider({ locale: 'de', messages: getMessages('de') }, {});
const { intl } = intlProvider.getChildContext();
/**
* When using React-Intl `injectIntl` on components, props.intl is required.
*/
function nodeWithIntlProp(node) {
return React.cloneElement(node, { intl });
}
export function shallowWithIntl(node, { context } = {}) {
return shallow(nodeWithIntlProp(node), {
context: Object.assign({}, context, { intl }),
});
}
export function mountWithIntl(node, { context, childContextTypes } = {}) {
return mount(nodeWithIntlProp(node), {
context: Object.assign({}, context, { intl }),
childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes),
});
}
export const createComponentWithIntl = (children, props = { locale: 'de' }) =>
renderer.create(<IntlProvider {...props}>{children}</IntlProvider>);
export const mockIntlShape = {
formatDate: jest.fn(),
formatTime: jest.fn(),
formatRelative: jest.fn(),
formatNumber: jest.fn(),
formatPlural: jest.fn(),
formatMessage: jest.fn(),
formatHTMLMessage: jest.fn(),
now: jest.fn(),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment