【问题标题】:Testing react-intl components with enzyme用酶测试 react-intl 组件
【发布时间】:2016-08-20 08:47:39
【问题描述】:

我查看了 react-intl 的建议,但它没有为 enzyme 留下任何明确的文档。

这就是我一直在尝试编写测试的方式。

import {IntlProvider} from 'react-intl';

const intlProvider = new IntlProvider({locale: 'en'}, {});
const intl = intlProvider.getChildContext();
const customMessage = shallow(<CustomMessage />, { options: { context: intl } });

但我不断收到错误

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

我查看了他们的仓库,他们似乎有 made it work 和 'react-addons-test-utils'。

我做错了吗?

【问题讨论】:

    标签: unit-testing reactjs enzyme react-intl


    【解决方案1】:

    我通过使用得到它的工作

    const customMessage = shallow(<CustomMessage />, { context: intl });
    

    改为。

    【讨论】:

    • 这是shallow 实例化的好方法。注意这在使用 Enzyme 的 mount 方法时不起作用。
    【解决方案2】:

    我已经发布了一个类似问题的答案:

    Injecting react-intl object into mounted Enzyme components for testing

    您可以import { shallowWithIntl } from 'intl-helper',然后使用shallowWithIntl(),而不是Enzyme 的shallow()

    【讨论】:

    • 有没有人在 TypeScript 中有像 shallowWithIntlmountWithIntl 这样的助手?
    【解决方案3】:

    这就是我实现目标的方式:

    
    import React from 'react';
    import StandardFilterIntl, {StandardFilter} from 'bundles/components/Filter/StandardFilter';
    import {mountWithIntl} from 'enzyme-react-intl';
    
    const FilterComponent = mountWithIntl(<StandardFilterIntl {...standardFilterProps} />);
    FilterComponent.find(StandardFilter).state()
    
    

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2023-03-24
      • 2018-06-14
      • 1970-01-01
      • 2018-07-25
      • 2019-03-13
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      相关资源
      最近更新 更多