"Se um trabalhador quiser fazer bem o seu trabalho, ele deve primeiro afiar suas ferramentas." - Confúcio, "Os Analectos de Confúcio. Lu Linggong"
Primeira página > Programação > React Basics ~ Teste de unidade/teste assíncrono

React Basics ~ Teste de unidade/teste assíncrono

Postado em 2025-03-12
Navegar:925
  • 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 ? (

Profile

  • ID: {userData.id}
  • Name: {userData.name}
> ) : (

...loading

)}
); }; export default GetUserData;

・ 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");
  });
});

    ;

React Basics~unit test/async test 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 (); const h1el = screen.getByRole ("cabeçalho", {name: "... carregando"}); Espere (H1el) .TobeInthEdocument (); }); ★ Usando async/aguardar teste ("Após a busca de dados externos", async () => { renderizar (); const h2el = Await screen.findbyRole ("cabeçalho", {name: "perfil"}); Espere (H2el) .TobeInthEdocument (); const itemels = Aguarda Screen.findallByRole ("ListItem"); Espere (Itemels [0] .TextContent) .Tobe ("Id: 1"); Espere (Itemels [1] .TextContent) .Tobe ("Nome: Foo"); }); });

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();
  });

  ★ 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");
  });
});

Se eu uso async/aguarda, o teste é bem -sucedido.

React Basics~unit test/async test

Mostrar

React Basics~unit test/async test

Declaração de lançamento Este artigo é reproduzido em: https://dev.to/kkr0423/react-basicsunit-testasync-test-28g?1 Se houver alguma violação, entre em contato com [email protected] para excluí-lo.
Tutorial mais recente Mais>

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