1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

queryAllByRoleとgetAllByRoleの違い

Last updated at Posted at 2025-04-27

はじめに

名前が似てるようで、機能が異なる queryAllByRolegetAllByRole の違いについてまとめました。

queryAllByRolegetAllByRoleの違い

- queryAllByRole

queryAllByRole はDOM上に要素が見つからなかった場合に空の配列 [] を返します。
つまり、要素が存在しない可能性がある状態をテストしたい場合はこちらを使用します。

afterDeleteButtons = screen.queryAllByRole("button", {
    name: "削除",
  });
console.log(afterDeleteButtons); // []が表示される

- getAllByRole

getAllByRole はDOM上に該当する要素が見つからなかった場合 TestingLibraryElementError というエラーがスローされます。
これは、 getAllByRole ファミリーのメソッド(getAllByRolegetAllByLabelTextgetAllByText など)の設計によるものです。

これらのメソッドは、1つ以上の要素が見つかることを期待しており、見つからなかった場合はテストが意図しない状態で進むのを防ぐためにエラーを発生させます。

afterDeleteButtons = screen.getAllByRole("button", {
    name: "削除",
  });
console.log(afterDeleteButtons); // エラーがスローされるのでテストが失敗する

おわりに

Jestの関数は多すぎて、なかなか覚えられない(笑)

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?