LoginSignup
0
1

More than 1 year has passed since last update.

【React】React Testing Libraryを使ってみる

Posted at

React Testing Libraryとは?

Reactアプリケーションをテストできるライブラリです。
Testing LibraryはVueなどのフレームワークでも利用することができます。

使用するコード

TestComponent.js

const TestComponent = () => {
  return (
    <div>
      <form>
        <h1>こんばんわ</h1>
        <h2>こんにちは</h2>
        <input type="radio" />
        <button>ボタン1</button>
        <button>ボタン2</button>
        <img src="/logo512.png" alt="React" />
      </form>
    </div>
  );
};

export default TestComponent;

テストの実行

テストを実行するファイルを作成します。名前をTestComponent.test.jsとします。
テストを実行するファイルであることが分かるようにtestを含めます。

import { render, screen } from "@testing-library/react";
import TestComponent from "./TestComponent";

test("TestComonentのテスト", () => {
    render(<TestComponent />);
    //テストの記述
});

今回使用するコンポーネントのTestComponentとテストのためのrenderscreenをimportします。

4行目のtest()にテストの記述をしていきます。

  • こんにちはのテスト
    まずは簡単にこんにちはをテストしたいと思います
<h2>こんにちは</h2>
const konnichiwa = screen.getByText("こんにちは");
expect(konnichiwa).toBeInTheDocument();

方法としてはscreen.getByText()としてこんにちはを挿入します。
それをkonnnichiwaという変数に格納しておきます。
その変数をexpect(変数名).toBeInTheDocument()で比較します。
成功するとコンソールに1passedと表示されます。

  • 失敗例
const konnichiwa = screen.getByText("おはようございます");
expect(konnichiwa).toBeInTheDocument();

比較する文字列を仮におはようございますとすると存在しないため、失敗します。

  • getByRoleでの取得
    次にgetByRoleで以下の2つの要素をテストします。
<h1>こんばんわ</h1>
<h2>こんにちは</h2>

getByRoleでテストするにはscreen.getByRole("heading")とします。
headingとすることで<h1>~<h6>までの要素を取得することができます。

const h1El = screen.getByRole("heading", { name: "こんばんわ" });
expect(h1El).toBeInTheDocument();

const h2El = screen.getByRole("heading", { name: "こんにちは" });
expect(h2El).toBeInTheDocument();

headingだけだと、どの要素を持ってくればいいのか分からないので{name:"こんばんわ"}の様に指定してあげます。

  • input要素
    input要素では以下のテストコードです。
const radioEl = screen.getByRole("radio");
expect(radioEl).toBeInTheDocument();

type=radioを指定してあげます。仮にJSX内に同じ要素がある場合は1番初めに書かれている要素が取得されます。

  • img要素
    img要素では以下のテストコードです。
const imgEl = screen.getByRole("img");
//Altの属性で取る
const imgEl2 = screen.getByAltText("React");

expect(imgEl).toBeInTheDocument();
expect(imgEl2).toBeInTheDocument();

getByAltTextでAltの文字列を指定して取得することもできます。

  • button要素
    button要素では以下のテストコードです。
const buttonEl1 = screen.getByRole("button", { name: "ボタン1" });
const buttonEl2 = screen.getByRole("button", { name: "ボタン2" });

expect(buttonEl1).toBeInTheDocument();
expect(buttonEl2).toBeInTheDocument();

コードにはbutton要素が2つあるのでこんにちは、こんばんわの時と同じように{name : ○○}でボタンの名前を指定します。

Testing Libraryにはクエリの優先順位があるようです。
1.getByRole
2.getByLabelText
3.getByPlaceholderText
4.getByText
5.getByDisplayValue

詳しくはこちらを参照

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