1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { useState } from "react"; const setTimeoutComponent: React.FC = () => { const [text, setText] = useState("初期値"); const updateText = async () => { setText("Loading..."); setTimeout(() => { setText("更新値"); }, 2000); }; return ( <div> <button onClick={updateText}>Update Text</button> <p>{text}</p> </div> ); }; export default AsyncComponent; |
テストコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import {render,screen,waitFor} from "@testing-library/react"; import userEvent from "@testing-library/user-event" import setTimeoutComponent from "./setTimeoutComponent" const user = userEvent.setup(); describe("setTimeoutComponent",()=>{ it("ボタンをクリックすると非同期処理が実行される",async ()=>{ render(<setTimeoutComponent />) expect(screen.getByText("初期値")).toBeInTheDocument(); const button = screen.getByRole("button"); await user.click(button) expect(screen.getByText("Loading...")).toBeInTheDocument(); await waitFor(()=>{ expect(screen.getByText("更新値")).toBeInTheDocument(); },{ interval: 50, timeout: 3000 }) }) }) |
waitFor
setTimeoutの結果を待ちます。
interval
リトライまでの間隔をミリ秒で指定
timeout
タイムアウトまでの時間をミリ秒で指定。テスト対象のコードのsetTimeoutのミリ秒が2000になっているので余裕をもって3000などと指定します。
注意点
waitForを使ったテストは実時間を使うのでテスト時間が長くなりがちになります。本当にこのテストは必要かどうかを改めて検討していく必要があります。
この記事へのコメントはありません。