React 测试库:return 渲染中没有任何内容。这通常意味着缺少 return 语句。或者,为了不渲染任何内容,return null
React Testing Library: Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null
我正在查看 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();
});
感谢任何帮助。
这可能是因为您在渲染组件之前有一些 ms 超时。
import { waitForElement } from '@testing-library/react';
test("renders an alert", async () => {
const { getByTestId } = render(<Alert />);
await waitForElement(() => getByTestId("alert"));
expect(getByTestId("alert")).toBeInTheDocument();
});
找到这篇文章解决了我的问题并通过了测试。 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>
);
我正在查看 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();
});
感谢任何帮助。
这可能是因为您在渲染组件之前有一些 ms 超时。
import { waitForElement } from '@testing-library/react';
test("renders an alert", async () => {
const { getByTestId } = render(<Alert />);
await waitForElement(() => getByTestId("alert"));
expect(getByTestId("alert")).toBeInTheDocument();
});
找到这篇文章解决了我的问题并通过了测试。 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>
);