我一直在用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;
但是什么也没发生。
经过几个小时的研究,我发现我需要更改的是我要求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;
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句