🌊

【React】JestとTesting Libraryを使った単体テストの書き方

に公開

Reactで単体テストを実施する方法をまとめました。

まずはReactアプリを生成します。

npx create-react-app test-sample-app

setupTests.jsというファイルが生成されます。

setupTests.js
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

package.jsonのdependenciesにテストに必要なライブラリが記述されています。

package.json
{
  "name": "test-tutorial-yt",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",

テストを行うには、テストをしたいファイル名と拡張子の間にtestをつけてファイルを生成します。ちなみにApp.test.jsはReactアプリをつくると、デフォルトで生成されているファイルです。

App.test.js
import { render, screen } from '@testing-library/react';
import App from './App';

// testの中にはテスト内容を記述する。基本的に英語で書く。
test('renders learn react link', () => {

  // Appコンポーネントをテストする
  render(<App />);

  // App.jsの中にあるlearn reactという文字列を取得している
  // 末尾の「/i」は小文字大文字を無視する正規表現
  const linkElement = screen.getByText(/learn react/i);

  // expect(期待する) toBeInTheDocumentはドム要素。つまり、linkElementは存在しているのかをチェックする
  expect(linkElement).toBeInTheDocument();
});

テストの実行は下記コマンドを実行します。

npm test

npm testを実行すると、下記のようにテスト結果が表示されます。

 PASS  src/App.test.js
  ✓ renders learn react link (43 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.876 s
Ran all test suites related to changed files.

Watch Usage
 › Press a to run all tests.
 › Press f to run only failed tests.
 › Press q to quit watch mode.
 › Press p to filter by a filename regex pattern.
 › Press t to filter by a test name regex pattern.
 › Press Enter to trigger a test run.

上記を解説すると、まず「1 passed, 1 total」となっている部分は、合計で1テストケースある内の1つのテストがクリアしたという意味です。

ちなみにpackage.jsonのtestのところにreact-scripts test --verboseを追記すると、どのテストファイルがテストに合格したのかがわかるようになります。

package.json
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --verbose",
    "eject": "react-scripts eject"
  },

以上がReactで単体テストを実施する方法についてでした。

Discussion