Create React AppからJest + Enzymeでテストを書き始める一番簡単なチュートリアル


React + Jest + Enzymeを試してみようと思ってチュートリアルの記事を漁ったところ、イマイチ楽をさせてくれるもの見つからなかったので、自分でチュートリアルを作りました。

多分これが一番簡単だと思います(フラグ)。
その分テストとしては虚無っています、本当にひとまず動かすだけですのでご注意ください。

関連記事はたくさん見つかるが、まず動く環境が無いと試すこともできない。。。
そんな方にオススメです。

なお手順は以下のUdemy講座を参考にしました。
https://www.udemy.com/course/react-testing-with-jest-and-enzyme/

Create React AppからJest + Enzymeでテストを書き始めるチュートリアル

ゴール

Jest + Enzymeで作成したReactのコンポーネントに対するテストがパスすること

実行環境

  • react: 16.12.0
  • create-react-app: 3.3.0
  • enzyme: 3.11.0
  • enzyme-adapter-react-16: 1.15.2
  • jest-enzyme: 7.1.2

create-react-app

ひとまずcreate-react-appでReactのプロジェクトを作成します。

npx create-react-app my-app
cd my-app

Enzyme関連のパッケージを追加

jestは初めから入ってるので、Enzyme関連のパッケージを追加します。
--devオプションを付けることで、package.jsonの"devDependencies"にパッケージを追加します。

yarn add --dev enzyme jest-enzyme enzyme-adapter-react-16

App.test.jsを編集する不要コードを削除する

create-react-appで自動生成されたApp.test.jsを、Enzymeを利用する形に編集します。
(なおテスト対象のAppコンポーネントは自動生成されたものをそのまま用います)


import React from 'react';
import App from './App';
import Enzyme, { shallow } from 'enzyme'
import EnzymeAdapter from 'enzyme-adapter-react-16'

Enzyme.configure({ adapter: new EnzymeAdapter() });

test('renders learn react link', () => {
  const wrapper = shallow(<App />);
  expect(wrapper).toBeTruthy();
});

編集差分は以下の通り

diff --git a/src/App.test.js b/src/App.test.js
index 4db7ebc..e1d63d0 100644
--- a/src/App.test.js
+++ b/src/App.test.js
@@ -1,9 +1,11 @@
 import React from 'react';
-import { render } from '@testing-library/react';
 import App from './App';
+import Enzyme, { shallow } from 'enzyme'
+import EnzymeAdapter from 'enzyme-adapter-react-16'
+
+Enzyme.configure({ adapter: new EnzymeAdapter() });

 test('renders learn react link', () => {
-  const { getByText } = render(<App />);
-  const linkElement = getByText(/learn react/i);
-  expect(linkElement).toBeInTheDocument();
+  const wrapper = shallow(<App />);
+  expect(wrapper).toBeTruthy();
 });

テストを実行

テストが正常にパスしました!

$ yarn test
 PASS  src/App.test.js
  ✓ renders learn react link (5ms)

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

テストコードの解説

これだけだと寂しいので簡単にテストコードを簡単に解説します。(蛇足かもしれない)

モジュールのインポート & アダプターの設定

 import React from 'react';
-import { render } from '@testing-library/react';
 import App from './App';
+import Enzyme, { shallow } from 'enzyme'
+import EnzymeAdapter from 'enzyme-adapter-react-16'
+
+Enzyme.configure({ adapter: new EnzymeAdapter() });

@testing-library/react'関連のimportは不要なので消します。

以降追加したコードはEnzymeの公式にある以下の記載を参考に追加しています。
Enzyme関連のモジュールをインポートした上で、Enzyme.configureを用いてadapterの設定を行います。

Finally, you need to configure enzyme to use the adapter you want it to use. To do this, you can use the top level configure(...) API.
```
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });
```

テストコード本体

 test('renders learn react link', () => {
-  const { getByText } = render(<App />);
-  const linkElement = getByText(/learn react/i);
-  expect(linkElement).toBeInTheDocument();
+  const wrapper = shallow(<App />);
+  expect(wrapper).toBeTruthy();
 });

まず@testing-library/react'を利用したコードは削除します。(3行分)

次に出てくるconst wrapper = shallow(<App />);でAppコンポーネントを作成しています。
(https://airbnb.io/enzyme/docs/api/shallow.html)

expect(wrapper).toBeTruthy();で作成したAppコンポーネントの存在確認を実施しています。
(https://jestjs.io/docs/ja/expect#tobetruthy)

最後に

本当にただ動かすだけですが、この手順に従えばひとまずReact/Jest/Enzymeのテスト環境を構築できるはずです。以降は欲しい内容に応じて公式ドキュメントや各種記事を参考にしていただければ、トライアンドエラーで進めるはずです!(投げやり)

参考資料

Enzyme 公式ドキュメント
https://airbnb.io/enzyme/

Jest公式ドキュメント
https://jestjs.io/docs/ja/getting-started

2019 Update! React Testing with Jest and Enzyme(Udemy)
https://www.udemy.com/course/react-testing-with-jest-and-enzyme/