0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jestの基本をざっくりと理解する

Posted at

はじめに

PHPUnitの学習はしましたがJestも使う機会があったので、同じタイミングで学習しました。
その学習の過程をまとめたのが本記事です。

Jestとは?

Jestは、Facebook(現Meta)が開発した、JavaScript・TypeScript向けのテスティングフレームワークです。主に フロントエンドアプリケーション(Reactなど) の単体テストやスナップショットテストに使われます。

この記事で学べること

Jestの基本的な書き方や、ユニットテストの方法が学べます。
実際のテストの具体例を見てテストとはどういうものなのか?をざっくりと把握できます。

動作環境

  • OS:macOS Sequoia 15.1.1
  • Node.js:22.6.0
  • npm:10.8.2
  • Jest:29.7.0

インストール方法

npmを使ったインストール手順

npm install --save-dev jest

以下のディレクトリが作成されます。

├── node_modules
├── package-lock.json
└── package.json

package.json に以下を追加

{
  "scripts": {
    "test": "jest"
  }
}

Jestの基本的な使い方

2つの数値を加算する関数をテストします。

sum.test.jssum.js
function sum(a, b) {
  return a + b;
}
module.exports = sum;

テストケースの作成

test関数の第一引数はテスト名(テストケースの説明)を入れます。
expectには「テストしたい値」を入れます。
toBeは「expectの値が3と厳密に等しいこと」をチェックするマッチャー

sum.test.js
const sum = require("./sum");
test("adds 1 + 2 to equal 3", () => {
  // expectが
  expect(sum(1, 2)).toBe(3);
});

テストの実行

npm testでテストを実行できます。

テスト結果(成功)

テストは成功していますが、ログの内容も記載しています。

> test
> jest

// ./sum.test.jsが「成功(PASS)」したことを示しています。
 PASS  ./sum.test.js

// "adds 1 + 2 to equal 3"という名前のテストが「成功」し、実行に3ミリ秒かかったことを示しています。
  ✓ adds 1 + 2 to equal 3 (3 ms)

Test Suites: 1 passed, 1 total // testファイル数
Tests:       1 passed, 1 total // test関数の数
Snapshots:   0 total
Time:        0.701 s
Ran all test suites.

テストが失敗した時の挙動も見てみる

const sum = require("./sum");
test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(4); // テストを失敗させる
});

テスト結果(失敗)

テストが落ちた箇所の行数や、期待値と受け取った値が表示されています。
ログを見ればどこが原因なのかが簡単に確認できますね。

 FAIL  ./sum.test.js
  ✕ adds 1 + 2 to equal 3 (7 ms)

  ● adds 1 + 2 to equal 3

    expect(received).toBe(expected) // Object.is equality

    Expected: 4
    Received: 3

      2 |
      3 | test("adds 1 + 2 to equal 3", () => {
    > 4 |   expect(sum(1, 2)).toBe(4);
        |                     ^
      5 | });
      6 |

      at Object.toBe (sum.test.js:4:21)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.654 s, estimated 1 s
Ran all test suites.

マッチャーとは?

PHPUnitではassertSame等のアサーションと呼ばれるものがありますが、Jestではマッチャーというものがある。
Jestは基本的にexpectマッチャーを合わせてアサーションになる。
上のテストケースで書いているtoBe()マッチャーと呼び、toBe()は値と型が一致するかを確認するマッチャーという事になります。
マッチャーは色々あるので都度調べる形が良いと思いますが、よく使いそうなものを表にまとめておきます。

マッチャー 用途・説明
toBe(value) 値と型が一致しているか(===) expect(5).toBe(5);
toEqual(value) オブジェクトや配列などの値の等価性を比較 expect({a: 1}).toEqual({a: 1});
toStrictEqual(value) toEqual に加えて undefined プロパティも厳密比較 expect({a: undefined}).toStrictEqual({a: undefined});
not 否定(どのマッチャーにもチェーン可) expect(3).not.toBe(5);
toBeNull() nullであるか expect(null).toBeNull();
toBeUndefined() undefinedであるか expect(undefined).toBeUndefined();
toBeDefined() undefined 以外であるか expect(5).toBeDefined();
toBeTruthy() truthy な値か expect('hello').toBeTruthy();
toBeFalsy() falsy な値か expect(0).toBeFalsy();
toContain(item) 配列または文字列に指定の値が含まれているか expect([1, 2, 3]).toContain(2);
toHaveLength(number) 配列や文字列の長さを検証 expect('abc').toHaveLength(3);
toMatch(regex) 文字列が正規表現にマッチするか expect('abc').toMatch(/a/);
toThrow([error]) 関数が例外を投げるか expect(() => throwError()).toThrow();
toBeGreaterThan(number) 数値が指定値より大きいか expect(10).toBeGreaterThan(5);
toBeLessThan(number) 数値が指定値より小さいか expect(3).toBeLessThan(5);
toBeCloseTo(number, digits) 浮動小数点の近似比較 expect(0.1 + 0.2).toBeCloseTo(0.3, 5);
toHaveProperty(keyPath, value?) オブジェクトに指定のプロパティがあるか expect(obj).toHaveProperty('a.b', 123);

まとめ

今回はJestを学習してみました。
PHPUnitを学習してすぐだったので、同じような概念や似た書き方も多いのでユニットテストを学習した初期よりはスムーズに入ってきました。

参考リンク

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?