iT邦幫忙

2023 iThome 鐵人賽

DAY 23
0
自我挑戰組

Unit Test 學習路系列 第 23

Day 22: Pointer(Mouse) Interactions

  • 分享至 

  • xImage
  •  

今天來練習模擬滑鼠點擊的測試寫法:

Pointer(Mouse) Interactions

情境:畫面上一個按鈕,點擊顯示+1數字於畫面上。

import { useState } from "react"

export default function Counter(){
    const [ counter, setCounter ] = useState(0);
    return(
        <>
            <h1>{counter}</h1>
            <button onClick={() => setCounter(pre => pre+1)}>Add 1</button>
        </>
    )
}

第一步測試:確認畫面上有 <h1> <button>

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./counter";

describe("Counter", () => {
    // (1) 檢查是否有正確顯示在畫面上,與初始值
    test("Render correctly!", () => {
        render(<Counter />);

        const counterEl = screen.getByRole("heading", {
            level: 1
        });
        expect(counterEl).toHaveTextContent("0"); // 記得要輸入的是字串型別

        const btnEl = screen.getByRole("button", {
            name: "Add 1"
        });
        expect(btnEl).toBeInTheDocument();
    });
});

測試結果:
PASS src/components/counter/counter.test.tsx

第二步測試:模擬使用者點擊按鈕,畫面會出現 +1 數字。

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./counter";

describe("Counter", () => {
    (2) 模擬使用者點擊按鈕,數字加一的效果
    test("Show the counter of 1 after clicking the button!", async() => {
        render(<Counter />);

        const btnEl = screen.getByRole("button", {
            name: "Add 1"
        });
        await userEvent.click(btnEl);

        const counterEl = screen.getByRole("heading", {
            level: 1
        });
        expect(counterEl).toHaveTextContent("1"); // 記得要輸入的是字串型別
    });
});  

測試結果:
PASS src/components/counter/counter.test.ts


參考資源


上一篇
Day 21: `user-event` 是什麼?
下一篇
Day 23: keyboard interaction
系列文
Unit Test 學習路31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言