2
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?

「TestingLibraryElementError: Unable to find an element by: [data-testid="title"]」の解決方法

2
Posted at

はじめに

jestで書いたテストが通らない。

問題

App.jsのテストファイルApp.test.jsでh1タグに書いてある内容のテストが通らない。

TestingLibraryElementError: Unable to find an element by: [data-testid="title"]

App.js

export function App() {

/*
~~~
省略(非同期処理を含む)
~~~
*/

  return (
    <>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <>
          <h1 data-testid="title">学習記録一覧</h1>
        </>
      )}
    </>
  );
}

App.test.js

describe("Title Test", () => {
  it("タイトルが学習記録一覧であること", () => {
    render(<App />);
    const title = screen.getByTestId("title");
    expect(title).toHaveTextContent("学習記録一覧");
  });
});

解決方法

getByTestIdをfindByTestIdに変更する

App.test.js

describe("Title Test", () => {
  it("タイトルが学習記録一覧であること", async () => {
    render(<App />);
    const title = await screen.findByTestId("title", undefined, {
      timeout: 5000,
    });
    expect(title).toHaveTextContent("学習記録一覧");
  });
});

使いどころ

getByTestId:テスト開始時に画面に既に存在している要素を取得するとき
findByTestId:要素の表示が遅延されるとき

おわりに

今回はloading状態によってh1の描画が遅延されるため、getByTestIdで要素を取得しようとしても存在しなかった。
なので、findByTestIdで要素が表示されるのを待って取得しないといけなかった。

2
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
2
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?