React Testing Libraryでよく使う文法10選 初心者向け
導入
Reactでのテストの書き方を復習を兼ねて、記載していきます。
React Testing Libraryでよく使う文法10選を紹介します。
間違った使い方があれば教えて頂きたいです。
React Testing Library
実践
今回ではコンポーネントの単体テストを想定して、React Testing Libraryを使ってテストしていきます。
1. render
要素をレンダリングしてくれる機能です。
レンダリングされているかどうか確認したい場合には便利です。
test('[A1_1]レンダリングされているか', () => {
render(<Footer />)
})
公式サイト
2. getByText
指定されたテキストに一致する要素を検索する機能です。
この場合だとMyComponentに/about/iがあるか検索してくれるテストです。
import {render, screen} from '@testing-library/react'
render(<MyComponent />)
const aboutAnchorNode = screen.getByText(/about/i)
公式サイト
3. getByRole
指定されたロールを持つ要素を検索してくれる機能です。
この場合だとMyComponentにdialogのロールがあるか検索してくれるテストです。
<div role="dialog">
<button>Close dialog</button>
</div>
import {render, screen} from '@testing-library/react'
render(<MyComponent />)
const dialogContainer = screen.getByRole('dialog')
公式サイト
4. getByLabelText
指定されたラベルを持つ要素を検索してくれる機能です。
この場合だとMyComponentにUsernameのラベルがあるか検索してくれるテストです。
getByText, getByRole, getByLabelText のどれでも要素を取得できるので、
状況にあった機能を使うのがおすすめです。
<input aria-label="Username" />
import {render, screen} from '@testing-library/react'
render(<Login />)
const inputNode = screen.getByLabelText('Username')
公式サイト
5. toHaveBeenCalledTimes
関数が特定の回数呼び出されたかどうかをアサートします。
下記の文だと、ボタンを一度クリックしたので、
toHaveBeenCalledTimes(1)と1回呼び出されているかというテストをしています
// ボタンをクリック
const button = screen.getByRole('button', { name: 'account-delete' })
fireEvent.click(button)
// testFunction が呼び出されたことを確認
expect(testFunction).toHaveBeenCalledTimes(1)
6. toHaveTextContent
要素のテキストコンテンツが特定の文字列と一致するかをアサートします。
下記だと、usernameの値が、名前:${username}として要素に入っているかをテストしています。
const username = 'テストユーザー'
const nameElement = screen.getByLabelText('name-text')
expect(nameElement).toHaveTextContent(`名前:${username}`)
7. toBeInTheDocument
DOM内に要素が存在するかをアサートします。
下記だとgetByText('About')が存在しているかどうかをテストしています。
const aboutLink = screen.getByText('About')
expect(aboutLink).toBeInTheDocument()
8. toMatchSnapshot
要素のレンダリング結果が、事前に保存されたスナップショットと一致するかをアサートします。
下記だとAccountMenuの要素が事前に保存されたスナップショットと一致しているかテストしています。
const { container } = render(<AccountMenu onClick={testFunction} />)
expect(container).toMatchSnapshot()
9. toBe
2つの値が厳密に等しいかをアサートします。
aboutLink.href要素が、'http://localhost/top' と等しいかどうかテストしています。
const aboutLink = screen.getByText('about')
expect(aboutLink.href).toBe('http://localhost/top')
10. toHaveAttribute
要素が指定された属性と値を持っているかをアサートします。
imageElementが、src属性にprofileImageの値を持っているかテストしています。
const imageElement = screen.getByAltText('プロフィール画像')
expect(imageElement).toHaveAttribute('src', profileImage)
Discussion