LoginSignup
3
2

More than 1 year has passed since last update.

初めてのReactのテスト

Last updated at Posted at 2022-04-25

内容

Reactのテストコードの作成から実行までの流れを忘却録として記録する。

○ユニットテスト
・JEST
(create-react-appで作成したプロジェクトにはJESTが含まれている)

○レンダリングテスト
・testing-library/react
(プロジェクト作成時にpackage.jsonに記載されている)

開発環境

PC:macOS Montery
エディター:Visual Studio Code

nodebrew: v1.0.1
nodejs: v15.14.0

JEST:プロジェクト生成時のバージョン

ディレクトリ構成

下記コマンドを実行して、作成されるプロジェクトの構成とする。
(Reactのチュートリアルの構成)

npx create-react-app my-app
my-app/
 ├ public/
 ├ src/
 │ ├ App.css
 │ ├ App.js
 │ ├ App.test.js
 │ ├ index.css
 │ ├ index.js
 │ ├ logo.svg
 │ ├ reportWebVitals.js
 │ └ setupTests.js
 ├ README.md
 ├ package-lock.json
 └ package.json

コード

レンダリングテスト

App.jsとApp.test.jsファイルを下記のように変更する。

src/App.js
import React from 'react';

export const App = () => {
  return <div>Hello React</div>;
}
src/App.test.js
import React from 'react';
import { render } from '@testing-library/react';

import { App } from './App';

describe('App', () => {
  test('renders App component', () => {
    render(<App />);
  });
});

ユニットテスト

TimesTwo.jsとTimesTwo.test.jsの2ファイルを作成して、以下のようにコードを書く。

src/TimesTwo.js
//値を2倍にする関数
export const TimesTwo = (value) => {
  return value * 2;
}
src/TimesTwo.test.js
import { TimesTwo } from './TimesTwo';

//引数2を倍の4にされたことを確認する(期待値の確認テスト)
test('TimesTwo test', () => {
  expect(TimesTwo(2)).toBe(4);
});

※テストコードのファイルは、「テストしたいファイル名.test.js」にする。
今回の場合はApp.jsをテストするので、App.test.jsになる。

テストコマンドの実行

npm test

実行結果

App.test.js
 PASS  src/App.test.js
  App
     renders App component (16 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.606 s
Ran all test suites.

Watch Usage: Press w to show more.
TimesTwo.test.js
 PASS src/TimesTwo.test.js
   first test (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.388 s
Ran all test suites.

Watch Usage: Press w to show more.

※ターミナル上でキーボードのQをクリックして、テストを終了できる。

#参考記事

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