Injecting react-intl object into mounted Enzyme components for testing

前端 未结 1 1039
广开言路
广开言路 2021-02-07 02:02

EDIT: Solved! Scroll down for the answer


In our Component tests we need them to have access to the react-intl context. The problem is that we are

1条回答
  •  情话喂你
    2021-02-07 03:05

    I have created a helper functions to patch the existing Enzyme mount() and shallow() function. We are now using these helper methods in all our tests where we use React Intl components.

    You can find the gist here: https://gist.github.com/mirague/c05f4da0d781a9b339b501f1d5d33c37


    For the sake of keeping data accessible, here's the code in a nutshell:

    helpers/intl-test.js

    /**
     * Components using the react-intl module require access to the intl context.
     * This is not available when mounting single components in Enzyme.
     * These helper functions aim to address that and wrap a valid,
     * English-locale intl context around them.
     */
    
    import React from 'react';
    import { IntlProvider, intlShape } from 'react-intl';
    import { mount, shallow } from 'enzyme';
    
    const messages = require('../locales/en'); // en.json
    const intlProvider = new IntlProvider({ locale: 'en', messages }, {});
    const { intl } = intlProvider.getChildContext();
    
    /**
     * When using React-Intl `injectIntl` on components, props.intl is required.
     */
    function nodeWithIntlProp(node) {
      return React.cloneElement(node, { intl });
    }
    
    export default {
      shallowWithIntl(node) {
        return shallow(nodeWithIntlProp(node), { context: { intl } });
      },
    
      mountWithIntl(node) {
        return mount(nodeWithIntlProp(node), {
          context: { intl },
          childContextTypes: { intl: intlShape }
        });
      }
    };
    

    CustomComponent

    class CustomComponent extends Component {
      state = {
        foo: 'bar'
      }
    
      render() {
        return (
          
    ); } }

    CustomComponentTest.js

    import { mountWithIntl } from 'helpers/intl-test';
    
    const wrapper = mountWithIntl(
      
    );
    
    expect(wrapper.state('foo')).to.equal('bar'); // OK
    expect(wrapper.text()).to.equal('Hello World!'); // OK
    

    0 讨论(0)
提交回复
热议问题