首頁  >  文章  >  web前端  >  React 基礎知識~單元測試/非同步測試

React 基礎知識~單元測試/非同步測試

Barbara Streisand
Barbara Streisand原創
2024-10-25 06:35:17572瀏覽
  • 當我測試非同步操作時,我在測試程式碼中使用 async/await。

  • 我需要準備測試資料。在本例中,我使用 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"
  },

然後我必須執行命令。

 npm run json-server

・src/Example.js

import GetUserData from "./components/GetUserData";

//The path of test data
export const ENDPOINT_URL = 'http://localhost:4030/users/1';

const Example = () => {
  return (
    <>
      <GetUserData url={ENDPOINT_URL}/>
    </>
  );
};

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 (
    <div>
      {userData ? (
        <>
          <h2>Profile</h2>
          <ul>
            <li>ID: {userData.id}</li>
            <li>Name: {userData.name}</li>
          </ul>
        </>
      ) : (
        <h1>...loading</h1>
      )}
    </div>
  );
};

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(<GetUserData url={ENDPOINT_URL} />);
    const h1El = screen.getByRole("heading", { name: "...loading" });
    expect(h1El).toBeInTheDocument();
  });

  ★ Not using  async/await
  test("After external data fetching",  () => {
    render(<GetUserData url={ENDPOINT_URL} />);
    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");
  });
});

  • 如果我不使用 async/await,測試會在 Expect(h2El).toBeInTheDocument(); 處失敗。

React Basics~unit test/async test

因為測試在沒有使用者資料的情況下繼續進行。

・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(<GetUserData url={ENDPOINT_URL} />);
    const h1El = screen.getByRole("heading", { name: "...loading" });
    expect(h1El).toBeInTheDocument();
  });

  ★ Using  async/await
  test("After external data fetching", async () => {
    render(<GetUserData url={ENDPOINT_URL} />);
    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");
  });
});

  • 如果我使用async/await,測驗就會成功。

React Basics~unit test/async test

  • 顯示

React Basics~unit test/async test

以上是React 基礎知識~單元測試/非同步測試的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn