React Components ကို UI ကနေ စမ်းပါ

19.3

တကယ်သုံးမယ့်သူ လုပ်သလို component ကို စမ်းပြီး screen ပေါ်မှာ မျှော်လင့်ထားတာ ပေါ်လား စစ်ပါ။

ဒီစာမျက်နှာမှာ

Vitest နဲ့ Testing Library ပြင်ဆင်ပါ

React နဲ့ Vite project မှာ DOM environment နဲ့ testing libraries တွေ install လုပ်ပါ။ အောက်က test ရဲ့ environment comment က အဲဒီဖိုင်အတွက် jsdom ဖွင့်ပါတယ်။ Cleanup hook က test တစ်ခုပြီးတိုင်း render လုပ်ထားတဲ့ component ကို ဖယ်ပါတယ်။

npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event
npx vitest run

Click လုပ်ပြီး မြင်ရတဲ့ ရလဒ်ကို စစ်ပါ

Button ကို role နဲ့ accessible name သုံးပြီး ရှာပါ။ User action ပြီးတဲ့အထိ await လုပ်ပြီး status text အသစ်ကို စစ်ပါ။ ဒီနမူနာကို quantity.test.jsx အဖြစ် သိမ်းပါ။ Network request ပါရင် UI ပြောင်းတဲ့အထိ စောင့်ပြီး အောင်မြင်တာနဲ့ မအောင်တာ နှစ်မျိုးလုံး စမ်းပါ။

// @vitest-environment jsdom
import React, { useState } from "react";
import { afterEach, expect, test } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

afterEach(cleanup);

function Quantity() {
  const [quantity, setQuantity] = useState(0);
  return (
    <>
      <button onClick={() => setQuantity(value => value + 1)}>Add one</button>
      <p role="status">{quantity}</p>
    </>
  );
}

test("adds one to the visible quantity", async () => {
  const user = userEvent.setup();
  render(<Quantity />);
  await user.click(screen.getByRole("button", { name: "Add one" }));
  expect(screen.getByRole("status").textContent).toBe("1");
});

တရားဝင် ကိုးကားချက်များ