Skip to content

Instantly share code, notes, and snippets.

@tsh-code
Created April 9, 2019 06:13
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 tsh-code/bd01f829cf85cdc77a46823254bf189e to your computer and use it in GitHub Desktop.
Save tsh-code/bd01f829cf85cdc77a46823254bf189e to your computer and use it in GitHub Desktop.
import React, { Fragment } from 'react';
const Intl = jest.genMockFromModule('react-intl');
const intl = {
formatMessage: ({ id, values }) => {
if (values) {
return JSON.stringify({ id, values });
}
return id;
},
locale: 'en',
};
Intl.injectIntl = Node => {
const renderWrapped = props => <Node {...props} intl={intl} />;
renderWrapped.displayName = Node.displayName || Node.name || 'Component';
return renderWrapped;
};
Intl.FormattedMessage = ({ id, tagName: TagName = 'span', values, children }) => {
const valuesString = !!values
? Object.entries(values || {}).map(([key, value], index) => {
if (React.isValidElement(value)) {
return <Fragment key={index}>{value}</Fragment>;
} else {
return JSON.stringify({ [key]: value });
}
})
: [null];
if (typeof children === 'function') {
return children(id, ...valuesString);
}
return (
<TagName>
{id}
{valuesString}
</TagName>
);
};
Intl.IntlProvider = props => <>{props.children}</>;
module.exports = Intl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment