使用自定义渲染器使用 react-testing-library 重新渲染

Use a custom render for rerender using react-testing-library

我正在使用 react-testing-library 并且我有一个自定义渲染器:

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

我可以在我的测试中成功地将它用于 render 但不能用于 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();
});

我收到 rerender 的错误 TypeError: Cannot read property 'black' of undefined。有什么方法可以让重新渲染器使用自定义渲染器,这样我就不必将每个重新渲染器都包装在 ThemeProvider?

您需要重新定义 rerender 方法。这应该有效:

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}),
    }
  };