9

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

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

这个库的文档说我们必须在根项目中创建一个名为的文件夹__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;

但什么也没有发生。

4

1 回答 1

21

经过几个小时的研究,我发现我需要改变的是我需要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;

希望这可以帮助!

于 2017-05-03T13:08:16.340 回答