【问题标题】:React+TS+i18n, How to test a component wrapped with react-intlReact+TS+i18n,如何测试用 react-intl 包裹的组件
【发布时间】:2021-09-22 09:11:32
【问题描述】:

组件看起来像

const Title = (props: TitleProps) => {
    return (
        <div>
            <span>{props.title}</span>
            <span>
                <FormattedMessage {...messages.date}></FormattedMessage>: {props.date}
            </span>
        </div>
    );
};

export default Title;

这是一个非常基本的应用程序,使用react-intl 来实现 i18n 功能。 部分App.tsx

<IntlProvider>
            <div>
                 <Title data={titleItem}></Title>
            </div>
</IntlProvider>

作为这样一个基础组件,目前我只想测试一下初始化

const titleItem: TitleItem = {
    title: 'test',
    date: '2021-01-01'
};

test('should be initialized', () => {
    render(<Title data={titleItem} />);
    expect(screen.getByText("test")).toBeInTheDocument();
});

如果我运行测试,它会抛出

[React Intl] 找不到所需的 intl 对象。 需要存在于组件祖先中。

我该如何解决?

【问题讨论】:

    标签: reactjs typescript react-testing-library react-intl


    【解决方案1】:

    您需要将要测试的组件包装在 &lt;IntlProvider /&gt; 组件中。

    https://formatjs.io/docs/guides/testing#react-testing-library

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 1970-01-01
      • 2020-05-12
      • 2017-04-26
      • 2018-02-16
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多