はじめに
現在、Jestとreact-testing-libraryを導入して、テストを作成しています。
テスト実行時に出たエラーについて解決策をまとめます。
問題
下記のテストケースを実行したところ、"TypeError: expect(...).toHaveTextContent is not a function" のエラーが出ました。
sampleComponent.spec.jsx
import { render,screen } from "@testing-library/react"
import { Study } from "../Study"
import React from "react"
test("タイトルが表示されること",()=>{
render(<Study />)
const title = screen.getByTestId("title")
expect(title).toHaveTextContent("学習記録一覧")
})
解決方法
import "@testing-library/jest-dom"
を追加しました。
sampleComponent.spec.jsx
import { render,screen } from "@testing-library/react"
import { Study } from "../Study"
import React from "react"
import "@testing-library/jest-dom"
test("タイトルが表示されること",()=>{
render(<Study />)
const title = screen.getByTestId("title")
expect(title).toHaveTextContent("学習記録一覧")
})
おわりに
@testing-library/jest-domとは?
テスト時のコンポーネント状態を確認するための便利なメソッド(カスタムマッチャー)が含まれているライブラリです。
今回使用したメソッドtoHaveTextContent
は、特定の要素が指定したテキストを持っていることを検証するためのアサーションです。
(今回の例だと、"title"が"学習記録一覧"と一致しているかどうかをチェックしています。)
しかし、デフォルトではJestにはこのアサーションが組み込まれていません。
従って、 toHaveTextContent
を使用するためには、@testing-library/jest-domをインポートする必要があります。
参考