2
2

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×Jest】data-testidがめっちゃ使いやすいという話

Posted at

はじめに

TypeScriptのJest・Testing Libraryを使用したテストにおいて非常に便利だなと思った話の共有です。

問題

idやclassを振っていないHTMLタグをテストクラスから取得したい場合、Testing Libraryが用意している専用のメソッドを使うことで簡単に取得することができます!

例えば、以下のコンポーネント(ローディング中を表すスピナー)が画面上に表示されているかどうかの確認をしたい場合

LoadingSpinner.tsx
export const LoadingSpinner: FC = memo(() => {
  return (
    <Spinner
      thickness="4px"
      speed="0.65s"
      emptyColor="gray.200"
      color="teal.500"
      size="xl"
    />
  );
});

解決方法

取得したい要素にdata-testid属性を付与した上で、
Testing LibraryのgetByTestIdという専用のメソッドを使う。

LoadingSpinner.tsx
export const LoadingSpinner: FC = memo(() => {
  return (
    <Spinner
+     data-testid="loading-spinner"
      thickness="4px"
      speed="0.65s"
      emptyColor="gray.200"
      color="teal.500"
      size="xl"
    />
  );
});
テストクラス
import {screen} from '@testing-library/dom'
const loadingSpinner = screen.getByTestId("loading-spinner");

おわりに

どんな要素でもこの方法で取得できるようです。
これは使えそう!

参考

JISOUのメンバー募集中🔥

プログラミングコーチングJISOUではメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
気になる方はぜひHPからライン登録お願いします!👇

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?