Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - Using IntlProvider with react-testing-library

For abstraction purpose, the app I work on has a custom provider that wraps a couple of other providers (like IntlProvider and CookiesProvider). The version of react-intl we use in our app is still v2 ([email protected]). A simplified version of my App.js is:

App.js

return (
      <Provider
        value={{
          localeData,
          env,
          data
        }}>
          <IntlProvider locale={language} key={language} messages={allMessages}>
             {props.children}
          </IntlProvider>
      </Provider>
  )

I have setup a custom render to test components in my app. My custom render looks exactly as it is specified in the react-intl-docs. I have followed the official setup guides from react-testing-library.

import React from "react";
import {render} from "@testing-library/react";

import {MyProvider} from "MyProvider";

const MyTestProvider = ({children}) => {
  return <MyProvider>{children}</MyProvider>;
};

const myTestRender = (ui, options) => render(ui, {wrapper: MyTestProvider, ...options});

export * from "@testing-library/react";
export {myTestRender as render};

I then render my component under test as follows:

import {render as renderSC} from "test-utils";
import MyComponentUnderTest from 'MyComponentUnderTest';

test("does my component render", () => {
  const {getByText} = renderSC(<MyComponentUnderTest />);
});

I get an error from react-intl which indicates it is warning, but the component that is rendered in test is empty.

console.error
    Warning: IntlProvider.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.

This is what my component renders in test:

    <body>
      <div />
    </body>

Is anyone able to advise what I might be doing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think your exports make this problem, try these instead:

import React from "react";
import {render} from "@testing-library/react";

import {MyProvider} from "MyProvider";

const MyTestProvider = ({children}) => {
  return <MyProvider>{children}</MyProvider>;
};

const myTestRender = (ui, options) => render(ui, {wrapper: MyTestProvider, ...options});

export default myTestRender;

and then use your custom renderer this way:

import renderSC from "test-utils";
import MyComponentUnderTest from 'MyComponentUnderTest';

test("does my component render", () => {
  const {getByText} = renderSC(<MyComponentUnderTest />);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...