hatellla
hatellla

Reputation: 5142

How to use translation with component to make it useful for unit testing

Most of the components looks like as follows:

import React, { Component } from "react";
import { withTranslation } from "react-i18next";

class XYZ extends Component {
    constructor(props) {
    super(props);
    this.state = {
    };
  }

  .....
  .....


  render() {
    const { t } = this.props;

    return (

        ..... 
    );
  }
}

export default withTranslation()(XYZ);

or, like below, in case of function components:

export const XYZ = withTranslation()(({ t, ...props }) => {
  ....
  return (
    .....
  );
});

I wanted to use enzyme shallow as it would only unit test the XYZ component than its child components but with it I face a problem as the first level of component is translation and it doesn't go to Child components inside XYZ. So, I am thinking I may not be writing the components properly. What do you suggest is the right way to write this class and function component so that testing would be easy.

Upvotes: 0

Views: 332

Answers (1)

Drew Reese
Drew Reese

Reputation: 203099

I find the container pattern to be rather useful for unit testing. Export the raw component and default export the decorated component.

export const MyComponent = props => (...);

export default componentDecorator(MyComponent);

The default export is for normal app consumption while the regular export is for testing. This allows you to mock all the props you need, or provide test wrappers to inject props normally accessed via context providers.

import { MyComponent } from '.'
...
shallow(<MyComponent {...mockTranslationProps} {...otherProps) />)

In projects I'm a part of we use react-intl for our translations, which as an injectItnl HOC that provides a intl.formatMessage function, for the tests I just create a mock intl object where the translation function simply passes it's argument through.

Upvotes: 2

Related Questions