找不到所需的 `intl` 对象。 <IntlProvider> 需要存在于组件祖先中。使用 wrapper.html()

Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry. while using wrapper.html()

我正在为 React 项目实施单元测试,使用 jest 和 enzyme。我正在使用 react-intl 来支持多语言。

我的基本单元测试代码是

import React from 'react'; 
import MobileRechargeComponent from './'; 
import {  shallowWithIntl, mountWithIntl } from '../../../../setupTestsHelper'; 

const wrapper = shallowWithIntl(<MobileRechargeComponent />); 
describe('Title', () => {
    it("should render initial layout", () => {
        expect(wrapper.getElements()).toMatchSnapshot();
    });
    it('renders master components properly', () => {
        console.log('wrapper>>>>>>>>>>>>>>>>>', wrapper.html())
        expect(wrapper.length).toEqual(1);
    }); 
});

我收到如下图所示的错误

我的setupTestsHelper文件代码如下

import React from 'react'; 
import { IntlProvider, intlShape, createIntl } from 'react-intl'; 
import { mount, shallow } from 'enzyme';
import { getCurrentLanguage } from './Lang'; 

const LocalLanguage = {
    french: {},
    arabic: {},
    english: {}
}

const lang = getCurrentLanguage('en', LocalLanguage)
const intl = createIntl({ locale: 'en', lang }, {});
const nodeWithIntlProp = (node) => {
    return React.cloneElement(node, { intl });
}
export const shallowWithIntl = (node) => {
    return shallow(nodeWithIntlProp(node), { context: { intl } });
} 
export const mountWithIntl = (node) => {
    return mount(nodeWithIntlProp(node), {
        context: { intl },
        childContextTypes: { intl: intlShape }
    });
}

需要实现自定义intl函数,连接react-intl的intl对象

为此,请在您的 setupTestsHelper 文件中添加此函数

import { IntlProvider } from 'react-intl';
const messages = require('./Lang/en.json') // en.json 
const defaultLocale = 'en'

const locale = defaultLocale

export const intl = (component) => {
     return (
         <IntlProvider
             locale={locale}
             messages={messages}
         >
             {React.cloneElement(component)}
         </IntlProvider>
     );
}

并在 *.test.js 文件中使用它,如下所示

    import {  intl } from '../../../../setupTestsHelper';

    const wrapper = mount(intl(<MyComponent />));