如何在组件中使用翻译以使其对单元测试有用 [英] How to use translation with component to make it useful for unit testing

查看:108
本文介绍了如何在组件中使用翻译以使其对单元测试有用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数组件如下所示:

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 (
    .....
  );
});

我想使用浅酶,因为它只能对XYZ组件进行测试而不是对其子组件进行测试,但是我遇到了一个问题,因为组件的第一级是翻译,并且它没有进入XYZ中的子组件。因此,我认为我可能没有正确编写组件。您建议的是编写此类和函数组件的正确方法,这样测试就容易了。

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.

推荐答案

我发现容器模式对于单元测试非常有用。导出原始组件,并默认导出装饰组件。

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) />)

在项目中,我是我们的一部分,我们使用react-intl进行翻译,将其作为 injectItnl HOC提供了 intl.formatMessage 函数,对于测试,我只是创建了一个模拟的intl对象,其中转换函数只是将其参数传递给了该对象。

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.

这篇关于如何在组件中使用翻译以使其对单元测试有用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆