使用 Jest 手动模拟 React-Intl 进行快照测试
Manual mock React-Intl with Jest to have snapshot testing
我一直在努力模拟 React-Intl library with 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;
但是没有任何反应。
查看它几个小时后,我发现我需要更改的是我需要 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;
希望对您有所帮助!
我一直在努力模拟 React-Intl library with 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;
但是没有任何反应。
查看它几个小时后,我发现我需要更改的是我需要 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;
希望对您有所帮助!