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

允我心安 提交于 2020-02-06 08:00:33

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/59773903/how-to-use-translation-with-component-to-make-it-useful-for-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!