Подтвердить что ты не робот

Инъекция объекта, реагирующего на взаимодействие, с установленными компонентами фермента для тестирования

EDIT: Решено! Прокрутите вниз для ответа


В наших тестах компонентов нам нужно, чтобы они имели доступ к контексту react-intl. Проблема в том, что мы монтируем отдельные компоненты (с Enzyme mount()) без их родительской оболочки <IntlProvider />. Это решается путем обертывания провайдера, но затем root указывает на экземпляр IntlProvider, а не на CustomComponent.

Тестирование с помощью React-Intl: Enzyme Документы по-прежнему пусты.

< CustomComponent/ >

class CustomComponent extends Component {
  state = {
    foo: 'bar'
  }

  render() {
    return (
      <div>
        <FormattedMessage id="world.hello" defaultMessage="Hello World!" />
      </div>
    );
  }
}

Стандартный тестовый пример (желаемый) (фермент + мокка + чай)

// This is how we mount components normally with Enzyme
const wrapper = mount(
  <CustomComponent
    params={params}
  />
);

expect( wrapper.state('foo') ).to.equal('bar');

Однако, поскольку наш компонент использует FormattedMessage как часть библиотеки react-intl, мы получаем эту ошибку при запуске вышеуказанного кода:

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


Обертка с помощью IntlProvider

const wrapper = mount(
  <IntlProvider locale="en">
    <CustomComponent
      params={params}
    />
  </IntlProvider>
);

Это предоставляет CustomComponent контекст intl, который он запрашивает. Однако при попытке выполнить такие утверждения теста, как эти:

expect( wrapper.state('foo') ).to.equal('bar');

вызывает следующее исключение:

AssertionError: expected undefined to equal ''

Это, конечно, потому, что он пытается прочитать состояние IntlProvider, а не наш CustomComponent.


Попытки доступа к CustomComponent

Я пробовал следующее безрезультатно:

const wrapper = mount(
  <IntlProvider locale="en">
    <CustomComponent
      params={params}
    />
  </IntlProvider>
);


// Below cases have all individually been tried to call `.state('foo')` on:
// expect( component.state('foo') ).to.equal('bar');

const component = wrapper.childAt(0); 
> Error: ReactWrapper::state() can only be called on the root

const component = wrapper.children();
> Error: ReactWrapper::state() can only be called on the root

const component = wrapper.children();
component.root = component;
> TypeError: Cannot read property 'getInstance' of null

Вопрос: Как мы можем монтировать CustomComponent с контекстом intl, все еще имея возможность выполнять "root" операции на нашем CustomComponent?

4b9b3361

Ответ 1

Я создал вспомогательные функции для исправления существующих функций Enzyme mount() и shallow(). Теперь мы используем эти вспомогательные методы во всех наших тестах, где мы используем компоненты React Intl.

Здесь вы можете найти суть: https://gist.github.com/mirague/c05f4da0d781a9b339b501f1d5d33c37


Для обеспечения доступности данных здесь код в двух словах:

хелперы/междунар-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 (
      <div>
        <FormattedMessage id="world.hello" defaultMessage="Hello World!" />
      </div>
    );
  }
}

CustomComponentTest.js

import { mountWithIntl } from 'helpers/intl-test';

const wrapper = mountWithIntl(
  <CustomComponent />
);

expect(wrapper.state('foo')).to.equal('bar'); // OK
expect(wrapper.text()).to.equal('Hello World!'); // OK