1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Jest × react-testing-library】toBeInTheDocument()のエラーとgetAllByTestIdの使い方

Last updated at Posted at 2025-02-09

はじめに

Next.jsReact Testing LibrarytoBeInTheDocument()を使用する際に発生したエラーについてまとめました。

この記事は個人的なアウトプットを目的として作成したものです。そのため、誤った情報や不足している内容が含まれている可能性があります。もし間違いや気になる点がございましたら、ぜひご指摘いただけますと幸いです

問題

取得したデータにタイトルがあることを確認するためのテストを実装しましたが、以下のエラーが発生しました。

Error: expect(received).toBeInTheDocument()

received value must be an HTMLElement or an SVGElement.
Received has type:  array

該当のコード

  it("タイトルがあること", async () => {
    render(<ArticleList />);

    await waitFor(() => {
      expect(global.fetch).toHaveBeenCalledTimes(1);
    });

    await waitFor(() => {
      expect(screen.getAllByTestId("title")).toBeInTheDocument();
    });
  });

原因

getAllByTestId()は 該当する要素を配列として返すため、toBeInTheDocument()を適用できないことが原因です。

解決方法

配列の要素数を確認するためにtoHaveLength()を使用すると、エラーを回避できます。

  it("タイトルがあること", async () => {
    render(<ArticleList />);

    await waitFor(() => {
      expect(global.fetch).toHaveBeenCalledTimes(1);
    });

    await waitFor(() => {
      expect(screen.getAllByTestId("title")).toHaveLength(2);
    });
  });

toHaveLength()を使用すると、要素の数が期待通りかを確認できます。

終わりに

これからもReact Testing Libraryのメソッドの使い分けを学習していきたいと思います。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?