如何解决React Testing库:渲染未返回任何内容这通常意味着缺少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>
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。