chai vs jasmine vs jest vs mocha
JavaScript テストツールチェーンの比較:ランナーとアサーション
chaijasminejestmocha類似パッケージ:

JavaScript テストツールチェーンの比較:ランナーとアサーション

jest と jasmine はテストランナーとアサーションを兼ね備えたフレームワークです。mocha は柔軟なテストランナーですが、アサーションには chai などの別ライブラリが必要です。chai は単体では動作せず、mocha と組み合わせて使われるアサーションライブラリです。これらを適切に組み合わせることで、プロジェクトの規模や要件に合わせたテスト環境を構築できます。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
chai08,265150 kB9510日前MIT
jasmine037873.6 kB02ヶ月前MIT
jest045,5526.7 kB22522日前MIT
mocha022,8901.44 MB2269日前MIT

JavaScript テストツール比較:Jest, Mocha, Jasmine, Chai

JavaScript のテスト環境を構築する際、jest、mocha、jasmine、chai のどれを選ぶべきかは、プロジェクトの構造と求める柔軟性によって決まります。これらは単なるライブラリではなく、テストの「実行方法」と「検証方法」を定義する重要なインフラです。それぞれの役割と違いを明確にして、適切な選択を行いましょう。

🏗️ 役割の整理:ランナー vs アサーション

まず根本的な違いを理解する必要があります。テストツールは大きく分けて「テストランナー」と「アサーションライブラリ」の 2 つの役割を持ちます。

  • テストランナー: テストファイルを見つけ、実行し、結果を報告します。
  • アサーションライブラリ: 期待値と実際の値を比較し、合否を判定します。

jest と jasmine はこの 2 つを両方備えた「オールインワン」フレームワークです。一方、mocha はランナー専門であり、chai はアサーション専門です。この違いが設定の複雑さや機能の幅に直結します。

📝 テストの記述スタイル:構造と構文

テストケースをどのように記述するかは、開発者の生産性に影響します。各パッケージが提供する構文を確認しましょう。

jest は test または it を使用し、グローバル関数として提供されます。

// jest: テスト構造
.test('ユーザー名が取得できること', () => {
  const user = getUser();
  expect(user.name).toBe('Alice');
});

mocha は describe と it を使用しますが、アサーションは含まれないため chai などを併用します。

// mocha + chai: テスト構造
import { expect } from 'chai';

describe('ユーザーモジュール', () => {
  it('ユーザー名が取得できること', () => {
    const user = getUser();
    expect(user.name).to.equal('Alice');
  });
});

jasmine も describe と it を提供し、構文は Mocha に似ていますが、アサーションは内蔵されています。

// jasmine: テスト構造
describe('ユーザーモジュール', () => {
  it('ユーザー名が取得できること', () => {
    const user = getUser();
    expect(user.name).toEqual('Alice');
  });
});

chai 単体ではテスト構造を持たず、アサーションのみを提供します。ランナーなしでは実行できません。

// chai: アサーションのみ(ランナー内で使用)
import { expect } from 'chai';

// 例:Mocha や Jest の内で使う
expect(value).to.equal(10);
expect(array).to.have.lengthOf(3);

✅ 期待値の検証:アサーションの書き方

値の比較方法もツールによって異なります。特にチェーン形式か否かが可読性に影響します。

jest は expect を使用し、マッチャーをチェーンします。シンプルで覚えやすいです。

// jest: アサーション
expect(count).toBe(5);
expect(items).toContain('apple');
expect(data).toHaveProperty('id');

mocha は単体ではアサーションを持たないため、通常 chai の expect を組み合わせて使います。

// mocha + chai: アサーション
import { expect } from 'chai';

expect(count).to.equal(5);
expect(items).to.include('apple');
expect(data).to.have.property('id');

jasmine は expect を提供しますが、マッチャーの名前が Jest と少し異なります。

// jasmine: アサーション
expect(count).toEqual(5);
expect(items).toContain('apple');
expect(data).toBeDefined();

chai は expect の他に assert や should スタイルも選べます。チームの好みに合わせられます。

// chai: 複数のアサーションスタイル
import { expect, assert } from 'chai';

// Expect style
expect(value).to.be.ok;

// Assert style
assert.equal(value, 10);

🎭 関数のモックとスパイ:依存関係の制御

外部依存を切り離すためのモック機能は、単体テストにおいて重要です。内蔵されているかどうかが大きな分かれ目です。

jest は強力なモック機能を内蔵しています。jest.fn() で簡単にスパイを作成できます。

// jest: 組み込みモック
const mockFn = jest.fn();
mockFn('hello');
expect(mockFn).toHaveBeenCalledWith('hello');

mocha はモック機能を内蔵していないため、sinon などの外部ライブラリが必要です。

// mocha + sinon: 外部ライブラリでモック
import sinon from 'sinon';

const stub = sinon.stub(obj, 'method');
obj.method();
expect(stub.calledOnce).to.be.true;

jasmine はスパイ機能を内蔵しています。spyOn を使用して既存の関数を監視できます。

// jasmine: 組み込みスパイ
spyOn(obj, 'method');
obj.method();
expect(obj.method).toHaveBeenCalled();

chai はアサーション専門のため、モック機能は提供しません。必ず外部ライブラリと組み合わせる必要があります。

// chai + sinon: 外部ライブラリでモック
import sinon from 'sinon';
import { expect } from 'chai';

const stub = sinon.stub();
stub();
expect(stub.called).to.be.true;

⚙️ 設定と拡張性:構成ファイルの違い

プロジェクトの要件に合わせて設定を調整できるかも選定基準になります。

jest は jest.config.js で設定します。デフォルトで多くの設定が含まれており、最小限の修正で動作します。

// jest: jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['./setup.js']
};

mocha は .mocharc.js またはコマンドラインオプションで設定します。ランナーとしての設定に特化しています。

// mocha: .mocharc.js
module.exports = {
  extension: ['js'],
  spec: 'test/**/*.test.js'
};

jasmine は jasmine.json で設定します。構成はシンプルですが、カスタマイズ性は Jest より低いです。

// jasmine: jasmine.json
{
  "spec_dir": "spec",
  "spec_files": ["**/*[sS]pec.js"]
}

chai はライブラリのため、設定ファイルは不要です。インポートして使用するだけです。

// chai: 設定不要
import { expect } from 'chai';
// プラグインを使う場合のみ設定が必要
import chaiPlugin from 'chai-plugin';
chai.use(chaiPlugin);

📊 機能比較サマリー

機能jestmochajasminechai
テストランナー✅ 内蔵✅ 内蔵✅ 内蔵❌ なし
アサーション✅ 内蔵❌ 外部必要✅ 内蔵✅ 専門
モック機能✅ 強力❌ 外部必要✅ 基本機能❌ 外部必要
設定ファイルjest.config.js.mocharc.jsjasmine.json不要
主な用途React, 一般 WebNode.js, 柔軟性重視Angular legacyMocha と併用

💡 最終推奨:プロジェクトに合わせた選択

テストツールの選択は、プロジェクトの技術スタックとチームの習熟度に依存します。

jest は現代の Web 開発、特に React エコシステムにおけるデファクトスタンダードです。設定が少なく、モック機能も充実しているため、新規プロジェクトではまずこれを検討すべきです。 — 迷ったら Jest で間違いないでしょう。

mocha と chai の組み合わせは、Node.js バックエンドや、テスト構成を細かく制御したい場合に有効です。既存のライブラリ資産を活かしたいプロジェクトでも重宝されます。 — 柔軟性が最優先ならこの組み合わせです。

jasmine は、外部依存を増やしたくない場合や、Angular の古いバージョンを維持している場合に適しています。 — 特定のレガシー環境では依然として有力な選択肢です。

どのツールを選ぶにしても、重要なのは「テストを書きやすく、維持しやすい環境」を作ることです。チームの状況に合わせて、最適な組み合わせを選定しましょう。

選び方: chai vs jasmine vs jest vs mocha

  • chai:

    Mocha と組み合わせて、自然言語に近い記述スタイルや豊富なアサーションメソッドが必要な場合に使用します。単体ではテストを実行できないため、ランナーとの併用が必須です。

  • jasmine:

    外部依存を最小限に抑えたオールインワン構成を好む場合や、Angular のレガシープロジェクト維持に適しています。Jest よりも設定がシンプルですが、機能拡張には工夫が必要です。

  • jest:

    React プロジェクトや設定の手間を省きたい場合に最適です。モック機能も内蔵されており、単体で完結するため導入コストが低いです。大規模なエコシステムがあり、コミュニティのサポートも厚いでしょう。

  • mocha:

    Node.js 環境で細かな設定制御が必要な場合や、既存のアサーションライブラリを使いたい場合に選択します。柔軟性が高い反面、設定ファイルの作成やライブラリの組み合わせが必要です。

chai のREADME

ChaiJS
chai

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

downloads:? node:?
Join the Slack chat Join the Gitter chat OpenCollective Backers

For more information or to download plugins, view the documentation.

What is Chai?

Chai is an assertion library, similar to Node's built-in assert. It makes testing much easier by giving you lots of assertions you can run against your code.

Installation

Node.js

chai is available on npm. To install it, type:

$ npm install --save-dev chai

Browsers

You can also use it within the browser; install via npm and use the index.js file found within the download. For example:

<script src="./node_modules/chai/index.js" type="module"></script>

Usage

Import the library in your code, and then pick one of the styles you'd like to use - either assert, expect or should:

import { assert } from 'chai';  // Using Assert style
import { expect } from 'chai';  // Using Expect style
import { should } from 'chai';  // Using Should style

Register the chai testing style globally

import 'chai/register-assert';  // Using Assert style
import 'chai/register-expect';  // Using Expect style
import 'chai/register-should';  // Using Should style

Import assertion styles as local variables

import { assert } from 'chai';  // Using Assert style
import { expect } from 'chai';  // Using Expect style
import { should } from 'chai';  // Using Should style
should();  // Modifies `Object.prototype`

import { expect, use } from 'chai';  // Creates local variables `expect` and `use`; useful for plugin use

Usage with Mocha

mocha spec.js --require chai/register-assert.js  # Using Assert style
mocha spec.js --require chai/register-expect.js  # Using Expect style
mocha spec.js --require chai/register-should.js  # Using Should style

Read more about these styles in our docs.

Plugins

Chai offers a robust Plugin architecture for extending Chai's assertions and interfaces.

  • Need a plugin? View the official plugin list.
  • Want to build a plugin? Read the plugin api documentation.
  • Have a plugin and want it listed? Simply add the following keywords to your package.json:
    • chai-plugin
    • browser if your plugin works in the browser as well as Node.js
    • browser-only if your plugin does not work with Node.js

Related Projects

Contributing

Thank you very much for considering to contribute!

Please make sure you follow our Code Of Conduct and we also strongly recommend reading our Contributing Guide.

Here are a few issues other contributors frequently ran into when opening pull requests:

  • Please do not commit changes to the chai.js build. We do it once per release.
  • Before pushing your commits, please make sure you rebase them.

Contributors

Please see the full Contributors Graph for our list of contributors.

Core Contributors

Feel free to reach out to any of the core contributors with your questions or concerns. We will do our best to respond in a timely manner.

Keith Cirkel James Garbutt Kristján Oddsson

Core Contributor Alumni

This project would not be what it is without the contributions from our prior core contributors, for whom we are forever grateful:

Jake Luer Veselin Todorov Lucas Fernandes da Costa Grant Snodgrass