如何在组件中使用翻译以使其对单元测试有用

问题描述 投票:0回答:1

大多数组件如下:

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

或者,如下所示,对于功能组件:

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

我想使用浅酶,因为它只能对XYZ组件而不是其子组件进行单元测试,但是随着它的出现,我面临一个问题,因为该组件的第一级是翻译,并且它不能用于XYZ内部的子组件。因此,我认为我可能没有正确编写组件。您建议的是编写此类和函数组件的正确方法,以便测试容易。

reactjs enzyme jest
1个回答
0
投票

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

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

export default componentDecorator(MyComponent);

默认导出用于常规应用程序的使用,而常规导出用于测试。这允许您模拟所需的所有道具,或提供测试包装器以注入通常可通过上下文提供程序访问的道具。

import { MyComponent } from '.'
...
shallow(<MyComponent {...translationProp} {...otherProps) />)
© www.soinside.com 2019 - 2024. All rights reserved.