0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Testing LibraryのqueryByTextとgetByTextの違い

Posted at

React Testing LibraryのqueryByTextとgetByTextの違いがわかっていなかったのでメモ。

queryByTextの場合は対象の文字列がなくてもエラーにはなりませんが、getByTextの場合は対象の文字列がなかった場合はエラーになります。

const Sample = () => {
  return <div>Sample</div>;
};

export default Sample;
import "@testing-library/jest-dom";
import Sample from "@/components/Sample";
import { render, screen } from "@testing-library/react";

describe("Sample", () => {
  it("queryByText", () => {
    render(<Sample />);

    expect(screen.queryByText("test")).not.toBeInTheDocument();
  });
  it("getByText", () => {
    render(<Sample />);

    expect(screen.getByText("test")).not.toBeInTheDocument();
  });
});

上記の2つのテストケースはどちらも文字列Sampleが見つからないためpassしそうですが、1つ目のケースはテストが通りましたが2つ目は下記エラーが発生しました。

TestingLibraryElementError: Unable to find an element with the text: test.
This could be because the text is broken up by multiple elements.
In this case, you can provide a function for your text matcher to make your matcher more flexible.
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?