我需要为测试数据做准备。在这种情况下,我使用JSON服务器。
・模拟/db.json
[2
{ "users": [ { "id": 1, "name": "Foo" } ] },然后我必须运行一个命令。
{ "users": [ { "id": 1, "name": "Foo" } ] }・ src/example.js
{ "users": [ { "id": 1, "name": "Foo" } ] }
= usestate(null);
useeffect(()=> {
axios.get(url)。
// eslint-disable-next-line反应钩/详尽的deps
},[]);
返回 (
import GetUserData from "./components/GetUserData"; //The path of test data export const ENDPOINT_URL = 'http://localhost:4030/users/1'; const Example = () => { return (> ); }; export default Example;
.TextContent).tobe(“ ID:1”);
期望(itemels [1] .textContent).tobe(“名称:foo”);
});
});
import { useEffect, useState } from "react"; import axios from "axios"; const GetUserData = ({ url }) => { const [userData, setUserData] = useState(null); useEffect(() => { axios.get(url).then((response) => setUserData(response.data)); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ([2{userData ? (); }; export default GetUserData;Profile
> ) : (
- ID: {userData.id}
- Name: {userData.name}
...loading
)}
因为测试在没有用户数据的情况下继续。
import { render, screen } from "@testing-library/react"; import GetUserData from "./GetUserData"; import { ENDPOINT_URL } from "../Example"; describe("Check an action of The GetUserData component", () => { test("External data fetching in progress", () => { render(.TextContent).tobe(“ ID:1”); 期望(itemels [1] .textContent).tobe(“名称:foo”); }); });); const h1El = screen.getByRole("heading", { name: "...loading" }); expect(h1El).toBeInTheDocument(); }); ★ Not using async/await test("After external data fetching", () => { render( ); const h2El = screen.findByRole("heading", { name: "Profile" }); expect(h2El).toBeInTheDocument(); const itemEls = screen.findAllByRole("listitem"); expect(itemEls[0].textContent).toBe("ID: 1"); expect(itemEls[1].textContent).toBe("Name: Foo"); }); });
[2
[2
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3