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

时间:2017-05-03 13:08:16

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

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

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;

但没有任何反应。

1 个答案:

答案 0 :(得分:5)

在看了几个小时之后,我发现我需要改变的是我需要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;

希望这有帮助!