LoginSignup
12
2

More than 1 year has passed since last update.

【React Testing Library】getBy, queryBy, findByの使い分け

Last updated at Posted at 2021-06-13

0. 背景

ReactでTesting Libraryを用いたテストコードを書いているときに、特定クエリに一致する要素を取得する方法として、getBy..., queryBy..., findBy...の3パターンある事に気がつきました。
3つの使い分け方を簡単に調べたので備忘録として残しておきます。

参考にしたページはTesting Libraryの公式ページとなっております。

1. それぞれの説明

※参照元: https://testing-library.com/docs/queries/about/

getBy

getBy...: Returns the matching node for a query, and throw a descriptive error if no elements match or if more than one match is found (use getAllBy instead if more than one element is expected).
getBy...: クエリにマッチするノードを返します。マッチする要素がない場合や、2つ以上のマッチが見つかった場合は、説明的なエラーを投げます。(Translated by DeepL)

queryBy

queryBy...: Returns the matching node for a query, and return null if no elements match. This is useful for asserting an element that is not present. Throws an error if more than one match is found (use queryAllBy instead if this is OK).
queryBy...: クエリに一致するノードを返し、一致する要素がない場合は null を返します。これは、存在しない要素をアサートする場合に便利です。複数のマッチが見つかった場合は、エラーをスローします。(Translated by DeepL)

findBy

findBy...: Returns a Promise which resolves when an element is found which matches the given query. The promise is rejected if no element is found or if more than one element is found after a default timeout of 1000ms.
findBy...: 指定されたクエリにマッチする要素が見つかったときに解決する Promise を返します。要素が見つからない場合や、デフォルトのタイムアウト(1000ms)後に複数の要素が見つかった場合には、Promiseは拒否されます。(Translated by DeepL)

2. 実際の使い方

以下のような使い分けにすれば良いのではないでしょうか?

  • getBy: 特定クエリに一致する要素を取得する時はこちらを使う
  • queryBy: 特定クエリに一致する要素がないことを取得する時はこちらを使う
  • findBy: 特定クエリに一致する要素を非同期で取得する時はこちらを使う

getBy: 一致する要素を取得

import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import Home from '../Home'

it('Should render hello text by getBy...', () => {
  render(<Home />)
  expect(screen.getByText('Hello by getBy!!')).toBeInTheDocument()
})

queryBy: 一致する要素がないことを取得する

import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import Home from '../Home'

it('Should NOT render hello text by queryBy...', () => {
  render(<Home />)
  expect(screen.queryByText('Hello by queryBy!!')).toBeNull()
})

findBy: 一致する要素を非同期で取得する

import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import Home from '../Home'

it('Should render hello text by findBy...', async () => {
  render(<Home />)
  expect(await screen.findByText('Hello by findBy!!')).toBeInTheDocument()
})

3. 最後に

それではみなさん素敵な(笑)テストライフを!!

12
2
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
12
2