Quando eu testo uma ação assíncrona, eu uso async/aguarda no código de teste.
eu preciso me preparar para os dados de teste. Nesse caso, eu uso um servidor JSON.
・ Mock/db.json
{ "users": [ { "id": 1, "name": "Foo" } ] }
・ package.json
"scripts": { "dev": "vite", "start": "vite", "build": "vite build", "test": "vitest", "preview": "vite preview", // ↓ setting a script for json server "json-server": "npx json-server -w ./mock/db.json -p 4030" },
e então eu tenho que executar um comando.
npm run json-server
・ src/exemplo.js
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;
・ src/components/getUserdata.jsx
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 ({userData ? (); }; export default GetUserData;Profile
> ) : (
- ID: {userData.id}
- Name: {userData.name}
...loading
)}
・ src/components/getUserdata.test.jsx
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(); 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"); }); });
porque o teste continua sem dados do usuário.
・ src/components/getUserdata.test.jsx
import {render, tela} de "@testing-library/react";
importar getUserData de "./getUserdata";
importar {endpoint_url} de "../example";
Descreva ("Verifique uma ação do componente getUserdata", () => {
teste ("dados externos que buscam em andamento", () => {
renderizar (
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(Se eu uso async/aguarda, o teste é bem -sucedido.); const h1El = screen.getByRole("heading", { name: "...loading" }); expect(h1El).toBeInTheDocument(); }); ★ Using async/await test("After external data fetching", async () => { render( ); const h2El = await screen.findByRole("heading", { name: "Profile" }); expect(h2El).toBeInTheDocument(); const itemEls = await screen.findAllByRole("listitem"); expect(itemEls[0].textContent).toBe("ID: 1"); expect(itemEls[1].textContent).toBe("Name: Foo"); }); });
Isenção de responsabilidade: Todos os recursos fornecidos são parcialmente provenientes da Internet. Se houver qualquer violação de seus direitos autorais ou outros direitos e interesses, explique os motivos detalhados e forneça prova de direitos autorais ou direitos e interesses e envie-a para o e-mail: [email protected]. Nós cuidaremos disso para você o mais rápido possível.
Copyright© 2022 湘ICP备2022001581号-3