我需要為測試數據做準備。在這種情況下,我使用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