LoginSignup
3
1

More than 3 years have passed since last update.

Materil-UIで作ったパスワードの入力フォームをreact-testing-libraryでテストするやり方

Posted at

使用環境 

(1)material-uiをインストールしている。
(2)react-testing-library と Jest をインストールしている
   ※(2)は、npx create-react-app を実行するとデフォルトでインストールされます。
(3)TypeScriptでコードが書かれている

目的

 Materil-UIの<Input/>で作ったパスワード入力フォーム<Input type="password">のテストコードをどうやって書くか説明すること

テスト対象のコンポーネント

 今回、テストを試みるのは、以下のコンポーネントです。

Auth.tsx

import React, { useState } from "react";
import { FormControl, InputLabel, Input } from "@material-ui/core";

const Auth: React.FC = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  return (
    <>
      <FormControl>
        <InputLabel htmlFor="password">パスワード</InputLabel>
        <Input
          id="password"
          type="password"
          value={password}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
            setPassword(e.target.value);
          }}
        />
      </FormControl>
    </>
  );
};

export default Auth;

試した方法① getByRole( )を使用→上手くいかない

Auth.test.tsx
import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Auth from "./Auth";

//その1 getByRollを試してみる
describe("入力フォームの更新イベント", () => {
  it("入力フォームに値が正しく入力されるか確認します", () => {
    render(<Auth />);
    const emailInput = screen.getAllByRole("textbox")[0];
    userEvent.type(emailInput, "test");
    expect(emailInput.value).toBe("test");
    const passwordInput = screnn.getAllByRole("textbox")[1];
    userEvent.type(passwordInput, "test");
    expect(passwordInput.value).toBe("test");
  });
});

まず最初にgetByRole()関数を使ってみたのですが、type="password"という属性が影響してか、テストコードで要素を取得することができませんでした。

どうすればいいんだ...。
ググった結果、以下のGitHubイシューのページに辿り着きました。
 *ByLabelText can't find password inputs

ざっくり読んだところ、type="password"属性を持ったinput要素を取得するためにはgetByLabelText()を使えばいいとのこと。早速試してみます。

試した方法② getByLabelText( )を使用→上手くいった!!

Auth.test.tsx
// その2 getByLabelTextを試してみる
describe("入力フォームの更新イベント",()=>{
  it("入力フォームに値が正しく入力されるか確認します",()=>{
    render(<Auth/>);
    const passwordInput = screen.getByLabelText("パスワード");
    userEvent.type(passwordInput,"test")
    expect(passwordInput.value).toBe("test");
  });
});

npm testを実行したところ、以下の画像のとおり、無事、PASSすることができました。

スクリーンショット 2021-03-26 1.36.46.png

所感 

今回はMaterial-UIの<Input/>コンポーネントと<InputLabel/>コンポーネントを使ったこともあり、通常の<input><label>ではないため、上手くいくか不安でしたが、杞憂だったみたいです。
id属性はテストコードを書く際にも、重要だと学ぶことができました!

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