LoginSignup
0
0

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

Last updated at Posted at 2024-05-01

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

テストの実施

前回テストを行う準備ができたので今回は関数単体テストを行っていきます。
いつも準備がつらいです。AIがいい感じに環境準備してくれないでしょうか。

関数単体のテスト

前回までのおさらい

加算の関数

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);
});

こんな感じのフォルダ構成
image.png

実行と実行結果

 npm run test

image.png

前回のテストコードの解説

Jestのテストは次の形式で書くようになっています。

test("テストタイトル", テスト用の関数)

テスト用の関数は次のように書きます。

  () => { expect(テストしたい値).toBe(期待する値); }
//() => { expect(add(1, 1)).toBe(2); } ※今回はテストしたい値がadd関数の実行結果

期待する値をわざと関数が返さない値にしてみると

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

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

実行結果

テスト失敗となります。
image.png

テストをグループ化する

例えば次の関数とテストを追加した場合

減算の関数

sub.ts
export function sub(x: number, y: number) {
  return x - y;
}

減算のテスト

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

test("1 - 1 は 0", () => {
  expect(sub(1, 1)).toBe(0);
});

実行結果

image.png

減算単体の実行結果

image.png

テストをまとめることができる

テストコード

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

describe("算数", () => {
  test("1 + 1 は 2", () => {
    expect(add(1, 1)).toBe(2);
  });
  test("1 - 1 は 0", () => {
    expect(sub(1, 1)).toBe(0);
  });
});

実行結果

見え方が異なる
1つのテストでチェックマークが2つ付くようになります。
image.png

条件分岐と例外処理

非同期処理のテスト

まとめ

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