使用Jest手动模拟React-Intl进行快照测试

Alb*_*ivé 3 javascript unit-testing reactjs jestjs react-intl

我一直在用Jest努力模拟React-Intl库,因为在运行测试时遇到此错误:

Invariant Violation: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.
Run Code Online (Sandbox Code Playgroud)

该库的文档说,我们必须在根项目中创建一个名为的文件夹__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;
Run Code Online (Sandbox Code Playgroud)

但是什么也没发生。

Alb*_*ivé 9

经过几个小时的研究,我发现我需要更改的是我要求react-intl包装的方式。因此,我更改了这一行:

const Intl = require.requireActual('react-intl');
Run Code Online (Sandbox Code Playgroud)

对此:

const Intl = jest.genMockFromModule('react-intl');
Run Code Online (Sandbox Code Playgroud)

因此,最终文件如下所示:

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;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!