Ошибка типа: intlProvider.getChildContext не является функцией - PullRequest
0 голосов
/ 09 января 2020

Я использую injectIntl ​​в своем функциональном компоненте реакции для достижения локализации. Я использую энзим / шут, чтобы сделать модульный тест. Я скопировал файл intl-test-helper, но получил ошибку: «TypeError: intlProvider.getChildContext не является функцией»

Я пробовал другие предложения из потока стека: 1. удалить макет файла --- у меня нет фиктивного файла 2. use const {IntlProvider} = jest.requireActual ("реагировать-intl"); чтобы заставить его использовать фактический, а не фиктивный - не работает.

компонент реакции: WarningModal.jsx:

import { FormattedMessage, injectIntl } from "react-intl";
.......

const WarningModal = ({
  .........
  ...props
}) => {
  ........

export default injectIntl(WarningModal);

intlTestHelper. 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"; // eslint-disable-line import/no-extraneous-dependencies

/** Create the IntlProvider to retrieve context for wrapping around. */
function createIntlContext(messages, locale) {
  const { IntlProvider } = jest.requireActual("react-intl");
  const intlProvider = new IntlProvider({ messages, locale }, {});
  const { intl } = intlProvider.getChildContext();
  return intl;
}

/** When using React-Intl `injectIntl` on components, props.intl is required. */
function nodeWithIntlProp(node, messages = {}, locale = "en") {
  return React.cloneElement(node, {
    intl: createIntlContext(messages, locale)
  });
}

/**
 * Create a shadow renderer that wraps a node with Intl provider context.
 * @param {ReactComponent} node - Any React Component
 * @param {Object} context
 * @param {Object} messages - A map with keys (id) and messages (value)
 * @param {string} locale - Locale string
 */
export function shallowWithIntl(
  node,
  { context } = {},
  messages = {},
  locale = "en"
) {
  return shallow(nodeWithIntlProp(node), {
    context: Object.assign({}, context, {
      intl: createIntlContext(messages, locale)
    })
  });
}

/**
 * Mount the node with Intl provider context.
 * @param {Component} node - Any React Component
 * @param {Object} context
 * @param {Object} messages - A map with keys (id) and messages (value)
 * @param {string} locale - Locale string
 */
export function mountWithIntl(
  node,
  { context, childContextTypes } = {},
  messages = {},
  locale = "en"
) {
  return mount(nodeWithIntlProp(node), {
    context: Object.assign({}, context, {
      intl: createIntlContext(messages, locale)
    }),
    childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes)
  });
}

вот как я использую его для проверки:

import React from "react";
import { _WM as WarningModal } from "../components/WarningModal";
// import { shallow } from "enzyme";
import { mountWithIntl } from "../utils/intlTestHelper.js";

describe("<WarningModal />", () => {
  const props = {
    discardChanges: jest.fn(),
    saveChanges: jest.fn(),
    closeWarningModal: jest.fn(),
    intl: { formatMessage: jest.fn() }
  };

  it("should have heading", () => {
    const wrapper = mountWithIntl(<WarningModal {...props} />);
    expect(wrapper.find(".confirm-title")).toBeTruthy();
  });
});

ошибка:

 ● <WarningModal /> › should have heading

    TypeError: intlProvider.getChildContext is not a function

      14 |   const { IntlProvider } = jest.requireActual("react-intl");
      15 |   const intlProvider = new IntlProvider({ messages, locale }, {});
    > 16 |   const { intl } = intlProvider.getChildContext();
         |                                 ^
      17 |   return intl;
      18 | }
      19 | 

      at getChildContext (src/utils/intlTestHelper.js:16:33)
      at createIntlContext (src/utils/intlTestHelper.js:23:11)
      at nodeWithIntlProp (src/utils/intlTestHelper.js:60:16)
      at Object.<anonymous> (src/tests/WarningModal.spec.js:29:21)

пожалуйста, подскажите несколько огней на этом. Спасибо.

1 Ответ

0 голосов
/ 10 января 2020

https://github.com/formatjs/react-intl/blob/master/docs/Testing-with-React-Intl.md содержит новую инструкцию для использования createIntl вместо

...