joetidee / enzyme-react-intl

A complimentary wrapper function for use with Enzyme, when testing React components that rely on react-intl
MIT License
45 stars 15 forks source link

Support for react-intl 3.x #28

Open Arrvi opened 5 years ago

Arrvi commented 5 years ago

This package is not compatible with current react-intl. When trying to mount, the function crashes on old API:

TypeError: o.getChildContext is not a function

   6 | import { testid } from '__tests__/utils'
   7 | 
>  8 | const component = mountWithIntl(<Pager page={1} totalPages={5} location={{ search: {} }}/>,
     |                   ^
   9 |     new ReactRouterEnzymeContext().get())
  10 | 
  11 | test('does not render for single page', () => {

  at mountWithIntl (node_modules/enzyme-react-intl/lib/webpack:/enzyme-react-intl/src/index.js:58:12)
  at Object.<anonymous> (app/pagination/components/Pager/__tests__/Pager.test.js:8:19)
Saebyuckbaan commented 5 years ago

On the top of Arrvi asked, react-intl has rewritten with Typescript in 3.x, could you also support Typescript natively?

ksocha commented 5 years ago

You can make it work by using Enzyme's getWrappingComponent and IntlProvider

e.g

const defaultMessages = new Proxy({}, { get: (target, property) => property });
let messages = defaultMessages;

export function loadTranslationObject(translations: object): object {
  if (typeof translations === 'undefined') {
    messages = defaultMessages;
    return defaultMessages;
  }

  messages = translations;
  return messages;
}

const WrappingComponent: React.FC = ({ children }) => (
  <IntlProvider locale="en" messages={messages}>
    {children}
  </IntlProvider>
);

export const mountWithIntl = (node: ReactElement) =>
  mount(node, { wrappingComponent: WrappingComponent });
AndyOGo commented 4 years ago

Is documented here officially: https://github.com/formatjs/react-intl/blob/master/docs/Testing-with-React-Intl.md#helper-function-1