我正在尝试测试一个组件,它使用useEffect
从api获取数据,然后api将数据保存在useState
中,这样我就可以Map这些数据并显示数据。
组分:
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import fetchContinents from "../../api/fetchContinents";
export const ContinentsList = () => {
const [continents, setContinent] = useState();
useEffect(() => {
fetchContinents().then((continent) => setContinent(continent));
}, []);
return (
<div className="flex justify-center items-center h-screen">
<ul className="w-1/4 md:w-1/2">
{continents?.data?.continents.map((continent) => {
return (
<Link to={`/countries/${continent.code}`}>
<div
key={continent.code}
className="bg-green-700 text-white rounded-2xl text-center mx-2 my-2 py-6 hover:bg-blue-500"
>
{continent.name}
</div>
</Link>
);
})}
</ul>
</div>
);
};
试验:
import { render, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";
import { ContinentsList } from "./ContinentsList";
describe("ContinentsList", () => {
test("Renders Africa on the page", async () => {
render(<ContinentsList />);
const africa = screen.getByText("Africa");
await waitFor(() => {
expect(africa).toBeInTheDocument();
});
});
});
测试运行程序输出:
组件在页面上呈现此内容:
因此,我认为问题是组件在useEffect
完成获取数据之前呈现,并且在DOM中没有任何内容,因此在Assert时,我搜索了一下,添加了waitFor
,我认为应该稍等片刻再进行评估,但它是react testing library
1条答案
按热度按时间bweufnob1#
这总是有点令人困惑。我的写作略有不同,我相信我有同样的问题:
而不是这样写:
试着这样写: