LoginSignup
0
0

関数単体テスト(フロントエンドのテスト②)

Last updated at Posted at 2024-05-01

※この記事はドラフト版です。

関数単体テストの実施 準備

フロントエンドの言語がTypeScriptであるため
「Jest」というテストツールを使って関数のテストを行っていきます。

※3年前にとある案件でnode.jsでバックエンドの処理を作っていた際に
 後からJest導入が要件に追加され苦労した記憶。。。

Jestのインストール

※node.jsがインストールされている前提です。

npm install --save-dev jest ts-jest @types/jest ts-node

Jestの設定を行う

スクリプトを追加する

package.json
{
  "scripts": {
    "test": "jest"
  }
}

Jestの設定ファイルを作成する

npx ts-jest config:init

次のファイルが作成される

jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
};

Jestを使ってみる

前の手順までで、Jestの準備が終わりました。
実際にJestを試していきます。

関数の作成

Jestにかける用の関数を作っていきます。

add.ts
export function add(x: number, y: number) {
  return x + y;
}

テストコードの作成

先ほど作成した関数をテストするコードを書いていきます。

add.test.ts
import { add } from "./add";

test("1 + 1 は 2", () => {
  expect(add(1, 1)).toBe(2);
});

テストの実行

npm run test

image.png
下記の警告が表示

ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.

TypeScriptの設定ファイルの作成

npx tsc --init

image.png

再度テストの実施

npm run test

警告が消えた
image.png

VSCodeのjestの拡張機能のインストール

image.png
Runボタンを押すと、該当のテストケースだけ実行してくれる
image.png
image.png

まとめ

テストの実施の記事のつもりでしたが、準備だけで終わりました。
Jestの設定が初期値なので不安がありますが、動いているのでOKとします。
今後、テストを行う中で不具合がでたら対応する方向で行きます。

次の予定は加算だけでなくいくつかの関数を書いて、関数毎にテストを書いていく予定です。

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