【问题标题】:Manual mock React-Intl with Jest to have snapshot testing使用 Jest 手动模拟 React-Intl 进行快照测试
【发布时间】:2017-10-01 08:12:34
【问题描述】:

我一直在努力嘲笑 React-Intl libraryJest,因为我在运行测试时遇到了这个错误:

Invariant Violation: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.

这个库的documentation 说我们必须在根项目中创建一个名为__Mocks__ 的文件夹,然后添加这个文件:

// ./__mocks__/react-intl.js
import React from 'react';
const Intl = require.requireActual('react-intl');

// Here goes intl context injected into component, feel free to extend
const intl = {
  formatMessage: ({defaultMessage}) => defaultMessage
};

Intl.injectIntl = (Node) => (props) => <Node {...props} intl={intl}/>;

module.exports = Intl;

但是什么也没发生。

【问题讨论】:

    标签: javascript unit-testing reactjs jestjs react-intl


    【解决方案1】:

    经过几个小时的研究,我发现我需要改变的是我需要 react-intl 包的方式。所以,我改变了那行:

    const Intl = require.requireActual('react-intl');
    

    到那个:

    const Intl = jest.genMockFromModule('react-intl');
    

    所以最终的文件是这样的:

    import React from 'react';
    const Intl = jest.genMockFromModule('react-intl'); // <-- This is the change
    
    const intl = {
      formatMessage: ({defaultMessage}) => defaultMessage
    };
    
    Intl.injectIntl = (Node) => (props) => <Node {...props} intl={intl}/>;
    
    module.exports = Intl;
    

    希望这会有所帮助!

    【讨论】:

    • 你必须使用const Intl = jest.genMockFromModule('react-intl');
    • 如何让 Jsx 元素与 module.js 文件一起使用?由于未知字符“,Jest 无法运行测试
    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2019-09-01
    • 2021-12-10
    相关资源
    最近更新 更多