0
0

More than 1 year has passed since last update.

Jest React TypeScript 環境構築

Last updated at Posted at 2022-12-06

概要

ReactのテストフレームワークJestの環境構築を行います。

開発環境

IDE:GitHub CodeSpaces
OS:windows10
言語:TypeScript

├── @testing-library/jest-dom@5.16.5
├── @testing-library/react@13.4.0
├── @testing-library/user-event@13.5.0
├── @types/jest@29.2.3
├── @types/node@16.18.4
├── @types/react-dom@18.0.9
├── @types/react@18.0.25
├── jest@29.3.1
├── react-dom@18.2.0
├── react-scripts@5.0.1
├── react@18.2.0
├── UNMET DEPENDENCY test@jest
├── ts-jest@29.0.3
├── typescript@4.9.3
└── web-vitals@2.1.4

手順

Reactを構築する

以下のコマンドを実行

npx create-react-app my-app

githubのログ
https://github.com/RYA234/my_learning_React_with_jest_and_ReactTestingLibrary/commit/645507004e4d2d60e3ae070114fb15afca074490

Jestを構築する

以下のコマンドを実行

cd my-app

npm i jest @types/jest ts-jest -D

githubのログ
https://github.com/RYA234/my_learning_React_with_jest_and_ReactTestingLibrary/commit/f1eec85267fa74f8a6ec5ca658913896504c97f8

Jestを使う

プロダクトコード

2つの値を足し算するコードです。

foo.ts
export const sum
  = (...a: number[]) =>
    a.reduce((acc, val) => acc + val, 0);

テストコード

foo.test.ts
import { sum } from '../src/foo';

test('basic', () => {
  expect(sum(1,4)).toBe(5);
});

test('basic again', () => {
  expect(sum(1, 2)).toBe(3);
});

test('basic  Pattern', () => {
    expect(sum(100, 2)).toBe(102);
  }
);

my-app以下で以下のコマンドを実行

コマンド.
npm test

Good Pattern

補足:qボタンで戻る
jestSuccessPatern.gif

Bad Pattern

結果がエラーになるようテストコードの値をいじります。
jestFailPatern.gif

感想

環境構築が楽で良いですね。
30分でできました。詰まるところなかったです。

参考

react 導入
https://code.visualstudio.com/docs/nodejs/reactjs-tutorial
CodeSpacesはクラウド版VSCodeなので、VSCodeのやり方をそのまま流用できます。

jest 導入「TypeScript を使用する」の項目から
https://jestjs.io/ja/docs/getting-started

0
0
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
0
0