React Testing库:渲染未返回任何内容。这通常意味着缺少return语句。或者,不渲染任何内容,则返回null

时间:2020-09-14 05:55:47

标签: reactjs react-testing-library

我正在查看30 Seconds of Code: React中的“警报”组件。效果很好。

我写了一个测试,但是测试失败并显示错误。 Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null https://codesandbox.io/s/goofy-curie-zh2bo

test("renders an alert", () => {
  const { getByTestId } = render(<Alert />);
  expect(getByTestId("alert")).toBeInTheDocument();
});

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这可能是因为在呈现组件之前您有一些ms超时。

import { waitForElement } from '@testing-library/react';

test("renders an alert", async () => {
  const { getByTestId } = render(<Alert />);
  await waitForElement(() => getByTestId("alert"));
  expect(getByTestId("alert")).toBeInTheDocument();
});

答案 1 :(得分:0)

找到这篇文章解决了我的问题并通过了测试。 https://kentcdodds.com/blog/use-ternaries-rather-than-and-and-in-jsx

return (
    <div>
      {isShown ? (
        <div
          className={`alert ${type}${isLeaving ? "leaving" : ""}`}
          role="alert"
          data-testid="alert"
        >
          <button className="close" onClick={closeAlert} />
          {message}
        </div>
      ) : null}
    </div>
  );