Skip to content

Instantly share code, notes, and snippets.

@LauraBeatris
Last active October 30, 2023 11:48
Show Gist options
  • Save LauraBeatris/b41e6ee76af9a56d6dd25873bbe4cecf to your computer and use it in GitHub Desktop.
Save LauraBeatris/b41e6ee76af9a56d6dd25873bbe4cecf to your computer and use it in GitHub Desktop.
Mock for react-i18next tests
const React = require('react');
const reactI18next = require('react-i18next');
/*
Also, if you're changing the language, add that mock function before your test suit
jest.mock('react-i18next', () => ({
useTranslation: () => ({
t: key => key,
i18n: { changeLanguage: jest.fn() },
}),
}));
*/
const hasChildren = node =>
node && (node.children || (node.props && node.props.children));
const getChildren = node =>
node && node.children ? node.children : node.props && node.props.children;
const renderNodes = reactNodes => {
if (typeof reactNodes === 'string') {
return reactNodes;
}
return Object.keys(reactNodes).map((key, i) => {
const child = reactNodes[key];
const isElement = React.isValidElement(child);
if (typeof child === 'string') {
return child;
}
if (hasChildren(child)) {
const inner = renderNodes(getChildren(child));
return React.cloneElement(child, { ...child.props, key: i }, inner);
}
if (typeof child === 'object' && !isElement) {
return Object.keys(child).reduce(
(str, childKey) => `${str}${child[childKey]}`,
''
);
}
return child;
});
};
const useMock = [k => k, {}];
useMock.t = k => k;
useMock.i18n = {};
module.exports = {
// this mock makes sure any components using the translate HoC receive the t function as a prop
withTranslation: () => Component => props => (
<Component t={k => k} {...props} />
),
Trans: ({ children }) => renderNodes(children),
Translation: ({ children }) => children(k => k, { i18n: {} }),
useTranslation: () => useMock,
// mock if needed
I18nextProvider: reactI18next.I18nextProvider,
initReactI18next: reactI18next.initReactI18next,
setDefaults: reactI18next.setDefaults,
getDefaults: reactI18next.getDefaults,
setI18n: reactI18next.setI18n,
changeLanguage: reactI18next.getDefaults,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment