【Jestで単体テスト】React+TypeScriptのテストコードの書き方をまとめてみた

React

React+TypeScriptでフロントエンドエンジニアやっています。

単体テストしたいんだけど、おすすめの方法ある?

今回はそんな疑問に回答します。

結論から言うと「Jest」というテストライブラリを使用するのがおすすめです

なぜこの記事を書いたのか

フロントエンド(React+TypeScript)の単体テストの手法の一つとしてスナップショットテストがあるが、あまり使用したことがなかったため、自分の記事としてまとめておきたかった。

この記事でできること

テストライブラリ「Jest」を使用してスナップショットテストをおこなう

技術スタック

  • フロントエンド:React(またはNext.js) + TypeScript

Jestの基本事項

  • テストコードの作成と実行をおこなうテストライブラリ
  • ファイル名は xxxxx.spec.tsx
  • React.jsと相性が良い
  • インストールすればすぐ使用できる
  • 値の比較やスナップショットといったテストができる

準備すること

react-test-renderer をインストールする

$ npm i react-test-renderer

実装

プロジェクトソース構成

今回 app1 / components / index.js のテストコードを書きたいので

app1
  └┬ next.config.js
   ┝ node_modules
   ┝ package-lock.json
   ┝ package.json
   ┝ components
   |   └ Button
   |       └ index.js
   ┝ pages
   |   └┬ _app.js
   |    └ index.js
   └ styles
       └ xxxxx.css

★の位置にspecファイルを作成することにする。

app1
  └┬ next.config.js
   ┝ node_modules
   ┝ package-lock.json
   ┝ package.json
   ┝ components
   |   └ Button
   |       └┬ index.js
   |        └ index.spec.js ★
   ┝ pages
   |   └┬ _app.js
   |    └ index.js
   └ styles
       └ xxxxx.css

テストコードの全体像

import ◯◯◯◯ from △△△△;

describe('大タイトル', () => {
 test('小タイトル', () => {
  // テストコード
 };
 test('小タイトル', () => {
  // テストコード
 };
});

「// テストコード」の部分に、テスト内容(値のチェックやスナップショット実行)を記述する。

テストコードを書く

import TestRenderer from 'react-test-renderer';
import Button from components/Button;

describe('Snapshots Button', () => {
 test('test case 1', () => {
  const onClickButton1 = () => {
   // 処理
  };
  const tree = TestRenderer.create(
   <Button
    idName="button1"
    text="OK"
    onClickFunction={() => onClickButton1()}
   />,
  ).toJSON();

  expect(tree).toMatchSnapshot();
 });
});

上記はButton というコンポーネントにPropsを渡して、正常にコンポーネントの中身を描画できるか?を確認するテストとなる。

もし渡すPropsによってButtonコンポーネントの中で処理が分岐する場合は、分岐の数だけテストする必要がある。

複数のPropsのパターンをテストする場合はこのように記述する。

import TestRenderer from 'react-test-renderer';
import Button from components/Button;

describe('Snapshots Button', () => {
 test('test case 1', () => {
  const onClickButton1 = () => {
   // 処理
  };

  const tree = TestRenderer.create(
   <Button
    idName="button1"
    text="OK"
    onClickFunction={() => onClickButton1()}
   />,
  ).toJSON();

  expect(tree).toMatchSnapshot();
 });

 test('test case 2', () => {
  const onClickButton1 = () => {
   // 処理
  };

  const tree = TestRenderer.create(
   <Button
    idName="button2"
    text="Cancel"
    onClickFunction={() => onClickButton1()}
   />,
  ).toJSON();

  expect(tree).toMatchSnapshot();
 });
});

テストコードを実行する

ターミナルを起動して、「package.json」のあるディレクトリでコマンドを実行する

$ jest -u components/index.spec.js

一度スナップショットテストを実行したのち、ソースコードを修正した同じファイルを続けて実行する場合は「-u」をつけないで実行することで差分がコマンドプロンプトに出力される

$ jest components/index.spec.js

コメント

タイトルとURLをコピーしました