Use a custom render for rerender using react-testing-library
Asked Answered
R

2

5

I'm using react-testing-library and I have a custom render:

const customRender = (node, ...options) => {
  return render(
    <ThemeProvider theme={Theme}>
      <MemoryRouter>{node}</MemoryRouter>
    </ThemeProvider>,
    ...options
  );
};

I can use it successfully for a render in my test but not for a rerender:

test("shows content once data has loaded", () => {
  const { queryByTestId, rerender, debug } = render(
    <ConnectAccount
      currentUser={{
        loading: true
      }}
    />
  );

  expect(queryByTestId("content")).toBeNull();

  rerender(
    <ConnectAccount
      currentUser={{
        user: {
          name: "Test User"
        }
      }}
    />
  );

  debug();
});

I get an error TypeError: Cannot read property 'black' of undefined for the rerender. Is there any way for the rerender to use the custom render so I don't have to wrap every rerender in the ThemeProvider?

Ruelas answered 23/11, 2018 at 14:54 Comment(0)
N
8

You need to redifine the rerender method. This should work:

const customRender = (node, options) => {
  const rendered = render(
    <ThemeProvider theme={Theme}>
      <MemoryRouter>{node}</MemoryRouter>
    </ThemeProvider>,
    options);

  return {
    ...rendered,
    rerender: (ui, options) =>
      customRender(ui, {container: rendered.container, ...options}),
    }
  };
Nomography answered 23/11, 2018 at 16:45 Comment(1)
Github issue in react-testing-library project regarding this matter: github.com/testing-library/react-testing-library/issues/218Erfurt
D
3

Typescript version:

function AppProvider({ children }: { children: React.ReactNode }) {
  return (
    <OtherProvider>
      <ThemeProvider theme={Theme}>
        <MemoryRouter>{children}</MemoryRouter>
      </ThemeProvider>,
    </OtherProvider>
  );
}

function renderInProvider(
  ui: ReactElement,
  options?: Omit<RenderOptions, "wrapper">
) {
  return render(<AppProvider>{ui}</AppProvider>, options);
}
Donohoe answered 21/11, 2022 at 20:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.