1
1

【React testing library】type="number"のinputへのuserEvent.typeができない

Last updated at Posted at 2024-09-05

はじめに

Reactの自動テストを書いている際に、inputタグのtype=numberへの入力を行った際にうまくnumberの入力ができず困ったため記載します

問題

以下のコードで作ったtype=numberのinputに対して「-1」を入力してエラーを出すというテストを書きたかったが、テストでエラー発生

  <input type='number' data-testid='time-input' {...register("time", { required: '時間の入力は必須です', min: { value: 0, message: '時間は0以上である必要があります' } })}/>

書いたテスト文

it('input-error', async () => {
    await act(async() => {
     render(<App />);
    })
    await waitFor(async () => {
      const addButton = screen.getByTestId("add-button");
      await userEvent.click(addButton);
      const timeInput = screen.getByTestId("time-input");
      await userEvent.type(timeInput, "-1");
      await userEvent.click(screen.getByTestId("submit-button"));
      expect(screen.getByText("時間は0以上である必要があります")).toBeInTheDocument();
    });
  })

エラー文

 Unable to find an element with the text: 時間は0以上である必要があります. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    Ignored nodes: comments, script, style

原因

上手く入力できておらず、初期値がそのまま入っていた

解決方法

await userEvent.type(timeInput, "-1");

fireEvent.change(timeInput, { target: { value: '-1' } });
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1