Skip to content

Instantly share code, notes, and snippets.

@snbk97
Created December 18, 2021 06:00
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 snbk97/4903e9d3228efb77a66d01619a9d8039 to your computer and use it in GitHub Desktop.
Save snbk97/4903e9d3228efb77a66d01619a9d8039 to your computer and use it in GitHub Desktop.
Enzyme with React-Intl
import React from 'react'
import { mount, shallow } from 'enzyme';
import { IntlProvider, intlShape } from 'react-intl';
import EN from '../../locales/en-US'
import SW from '../../locales/sw-SW'
type ILang = 'en' | 'sw';
const langOptions = {
en: {
locale: EN.locale, // en-US
messages: EN.messages // sw-SW
},
sw: {
locale: SW.locale,
messages: SW.messages
}
}
function nodeWithIntlProp(node, intl) {
return React.cloneElement(node, { intl });
}
export function shallowWithIntl(node, lang: ILang) {
const langProvider = langOptions[lang];
const {locale, messages} = langProvider;
const intlProvider = new IntlProvider({ locale, messages }, {});
const { intl } = intlProvider.getChildContext();
return shallow(nodeWithIntlProp(node, intl), { context: { intl } });
}
export function mountWithIntl(node, lang: ILang) {
const langProvider = langOptions[lang];
const {locale, messages} = langProvider;
const intlProvider = new IntlProvider({ locale, messages }, {});
const { intl } = intlProvider.getChildContext();
return mount(nodeWithIntlProp(node, intl), {
context: { intl },
childContextTypes: { intl: intlShape }
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment