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

时间:2018-11-23 14:54:51

标签: 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();
});

我收到TypeError: Cannot read property 'black' of undefined的错误rerender。重新渲染是否可以使用自定义渲染,因此我不必将每个重新渲染都包装在ThemeProvider中?

1 个答案:

答案 0 :(得分:1)

您需要重新定义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}),
    }
  };