Reactコンポーネントは、JestとReact Testing Libraryを使ってテストを実施できます。
Create React Appで作成したコードを参考に、テストを実行してみましょう。
構成はReact+TypeScript+yarnにします。
テストコードのサンプルと実行方法
src
├── App.css
├── App.test.tsx //.test.tsxがテストコード
├── App.tsx
├── index.css
├── index.tsx
・・・Create React Appでコードを生成すると、App.test.tsxという名称でテストコードが生成されます。
React Testing Libraryは標準で含まれていますので、テストを実行をしてみましょう。
1. テスト実行のコマンド
yarn test {
  ・・・
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  ・・・
}
package.jsonのscriptsに、すでに”test”コマンドが設定されています。
“yarn test”でテストが実行されます。npmの場合は”npm run test”です。
No tests found related to files changed since last commit.
Press `a` to run all tests, or run Jest with `--watchAll`.
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.実行後、”a”のキーを押すと全てのテストが実行されます。
実行ログは下記のような感じ。
 PASS  src/App.test.tsx
  ✓ renders learn react link (46 ms)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.756 s
Ran all test suites.“w”→”q”で終了します。
2. watch modeが不要な場合
yarn test --watchAll=falsewatch modeが不要であれば、–watchAll=falseのオプションで即実行できます。
3. 指定したファイルのみ実行
yarn test --watchAll=false src/App.test.tsxファイルを指定することで、特定のファイルのみ実行できます。
テストコードの書き方
Create React Appで生成されたApp.test.tsxを参考に、コードの書き方を見ていきます。
1. Jestの基礎
describe('このコンポーネントをテストします', () => {
  test('テストケース1', () => {
    expect(value1).toBeTruthy();
  });
  test('テストケース2', () => {
    expect(value2).toBeFalsy();
  });
});テストケースはtestで記載して、期待する値はexpectでチェックします。
testで記載したテストケースは、describeでまとめることができます。
- test(name, fn, timeout):テストケース
 - describe(name, fn):複数のテストケースをまとめるブロック
 - expect(value):値をテストする関数。toBe○○のような関数と一緒に使う。
 
例えば、expect(value).toBeTruthy()は「valueがtrueである」ことを期待しています。
2. コンポーネントをレンダリング
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});
テストしたいコンポーネントは、render関数でレンダリングします。
レンダリングすることで、コンポーネントの要素を取得したりすることができるようになります。
3. 要素を取得する
test('renders learn react link', () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});
レンダリングした要素を取得するには、screenを使用します。
getByTextは、引数に指定した文字列または正規表現を表示している要素を取得します。
const linkElement = screen.getByText(/learn react/i);/learn react/i は、正規表現で大文字小文字区別なくマッチするものが取得されます。
  expect(linkElement).toBeInTheDocument();toBeInTheDocumentは、DOMに要素が含まれているかチェックします。
ここでは、getByTextで要素が取得できていればOKということになりますね。
ちなみに、screenを使わなくてもrenderの戻り値のRenderResultで色々できます。
const {getByText, queryByRole} = render(<App />);要素の取得や検索のメソッドは色々ありますので、こちらを参照ください。
ひとまず、基本的な押さえておくべきところは以上かなと思います。
もっと細かいところは別の記事で書いていきます。
以上!
  
  
  
  


コメント