mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-05-06 21:00:24 -04:00
Replace brittle client snapshot coverage with explicit assertions so the updated test stack no longer depends on snapshot state initialization. Update the react-i18next mock to avoid mutating function component defaultProps while preserving WrappedComponent metadata for layout tests.
68 lines
1.8 KiB
JavaScript
68 lines
1.8 KiB
JavaScript
import React from 'react';
|
|
|
|
// modified from https://github.com/i18next/react-i18next/blob/master/example/test-jest/src/__mocks__/react-i18next.js
|
|
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 withTranslation = () => Component => {
|
|
const WrappedComponent = props =>
|
|
React.createElement(Component, {
|
|
...props,
|
|
t: props.t ?? (str => str)
|
|
});
|
|
|
|
WrappedComponent.WrappedComponent = Component;
|
|
WrappedComponent.displayName = `withTranslation(${Component.displayName || Component.name || 'Component'})`;
|
|
|
|
return WrappedComponent;
|
|
};
|
|
|
|
const useTranslation = () => {
|
|
return {
|
|
t: str => str,
|
|
i18n: {
|
|
changeLanguage: () => new Promise(() => {})
|
|
}
|
|
};
|
|
};
|
|
|
|
const Trans = ({ children }) =>
|
|
Array.isArray(children) ? renderNodes(children) : renderNodes([children]);
|
|
|
|
// translate isn't being used anywhere, uncomment if needed
|
|
/* const translate = () => Component => props => (
|
|
<Component t={() => ''} {...props} />
|
|
); */
|
|
|
|
module.exports = { withTranslation, useTranslation, Trans };
|