3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React testing library でTypeError: expect(...).toHaveTextContent is not a functionが出た

Posted at

はじめに

現在、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をインポートする必要があります。

参考

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?