テキストボックスへの入力テスト
testing-library14からはusereventはsetupを事前にするように変更になり非同期関数になりました。(13まではsetupは不要で同期関数でした。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import React from "react"; import { render, screen, cleanup } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import Input from "./Input"; const user = userEvent.setup() describe("入力", () => { it("入力テスト", () => { render(<Input />); const inputValue = screen. getByRole("textbox"); await user.type(inputValue, "test"); expect(inputValue.value).toBe("test"); }); }); |
await user.type(inputValue, "test");
第一引数で指定したテキストボックスに対して第二引数の「test」という文字列を入力していることをシミュレートすることができます。ちなみに、「type」とは型という意味ではなく、ユーザーがタイピングするという意味のtypeです。
expect(inputValue.value).toBe("test");
toBeというマッチャを使えば値の一致をチェックすることができます。
セレクトボックスへの入力テスト
1 2 3 4 5 |
<select multiple id="id名"> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> </select> |
セレクトボックスへの入力の場合は以下のように記述します。
1 2 |
await user.selectOptions(screen.getByTestId('id名'), 'optionのvalueの値'); expect(screen.getByTestId('id名').selected).toBe(true) |
入力解除
1 2 |
await user.deselectOptions(screen.getByRole('id名'),'optionのvalueの値') expect(screen.getByTestId('id名').selected).toBe(false) |
入力後にフォーカスを外す。
1 |
await user.tab(); |
この記事へのコメントはありません。