chai vs jasmine vs jest vs mocha vs sinon
JavaScript テストツールの選び方 — 実行、断言、モックの比較
chaijasminejestmochasinon類似パッケージ:

JavaScript テストツールの選び方 — 実行、断言、モックの比較

jestmochachaijasminesinon は、JavaScript アプリケーションのテストを書くために使われる主要なツールです。jestjasmine はテスト実行から断言まで一通り揃ったフレームワークです。mocha はテスト実行に特化し、chai は断言、sinon はモック作成に特化したライブラリです。プロジェクトの規模や要件に合わせて、これらを単独または組み合わせて使用します。

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

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
chai08,266147 kB913ヶ月前MIT
jasmine038175.4 kB01ヶ月前MIT
jest045,3326.59 kB24322日前MIT
mocha022,8752.31 MB2325ヶ月前MIT
sinon09,7582.24 MB4615日前BSD-3-Clause

JavaScript テストツール完全比較 — 実行、断言、モックの仕組み

jestmochachaijasminesinon は、JavaScript のテスト環境を構成する代表的なツール群です。これらはそれぞれ役割が異なり、単独で使うものもあれば、組み合わせて使うものもあります。開発者が最初に直面するのは「どれを組み合わせればいいか」という疑問です。ここでは、実際のコード書きながら、各ツールの役割と違いを明確にします。

🏃 テストの実行構造 — ランナーの有無

テストを書くには、テストファイルを発見し、実行し、結果を報告する「テストランナー」が必要です。

jest はテストランナーを内蔵しています。ファイル名が *.test.js なら自動で検出します。

// jest: test.js

test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3);
});

mocha もテストランナーですが、設定が必要です。describeit を使います。

// mocha: test.js

describe('Array', () => {
  it('should return index when value is present', () => {
    //  assertion library needed here
  });
});

jasmine もテストランナーを内蔵しています。jest と似た構文を持ちます。

// jasmine: spec.js

describe('A suite', () => {
  it('contains spec with an expectation', () => {
    expect(true).toBe(true);
  });
});

chai はテストランナーではありません。断言ライブラリなので、mocha などで実行する必要があります。

// chai: test.js (used with mocha)

import { expect } from 'chai';
// mocha provides describe/it, chai provides expect

sinon もテストランナーではありません。モック作成ライブラリなので、ランナーと組み合わせて使います。

// sinon: test.js (used with mocha/jest)

import sinon from 'sinon';
// sinon provides stubs/spies, runner executes the test

✅ 断言(アサーション)の書き方

テストが成功したか失敗したかを判定するのが「断言」です。各ツールで書き方が異なります。

jestexpect 関数を使います。チェーン構文で読みやすく書けます。

// jest

const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeLessThan(5);

mocha 単体では Node.js の assert モジュールを使うことが多いですが、通常は chai と組みます。ここでは標準の assert を示します。

// mocha (with Node assert)

const assert = require('assert');
const value = 2 + 2;
assert.strictEqual(value, 4);

chai は自然言語に近い構文が特徴です。expectshouldassert の 3 種類から選べます。

// chai

import { expect } from 'chai';
const value = 2 + 2;
expect(value).to.equal(4);

jasmineexpect を使いますが、jest とは一部構文が異なります。

// jasmine

const value = 2 + 2;
expect(value).toBe(4);
expect(value).toBeGreaterThan(3);

sinon には sinon.assert がありますが、主にモックの検証に使います。

// sinon

import sinon from 'sinon';
const mock = sinon.mock(object);
mock.expects('method').once();
// sinon.assert.calledOnce(mock);

🎭 モックとスタブの作成

外部依存(API やデータベース)を偽物に置き換えるのが「モック」です。

jest はモック機能が内蔵されています。jest.fn() で簡単に関数を偽装できます。

// jest

const mockFn = jest.fn();
mockFn('a');
expect(mockFn).toHaveBeenCalledWith('a');

mocha にはモック機能がありません。通常 sinon を併用します。

// mocha (with sinon)

import sinon from 'sinon';
const stub = sinon.stub(object, 'method');
stub.returns('fake value');

chai にもモック機能はありません。sinon と組み合わせて使います。

// chai (with sinon)

import sinon from 'sinon';
const spy = sinon.spy(object, 'method');
// use chai to assert results

jasminespyOn を使います。jest と似ていますが、オブジェクトメソッドに仕掛けます。

// jasmine

spyOn(object, 'method').and.returnValue('fake value');

sinon はモック専門ライブラリです。スタブ、スパイ、モックを細かく制御できます。

// sinon

const stub = sinon.stub();
stub.withArgs('a').returns('b');

⚙️ 設定と拡張性

プロジェクトが大きくなると、設定の柔軟性が重要になります。

jest は設定が最小限で済みます。package.json に書くだけで動くことが多いです。

// jest: package.json

{
  "jest": {
    "verbose": true
  }
}

mocha は設定ファイル(.mocharc.js)で細かく制御できます。拡張機能も豊富です。

// mocha: .mocharc.js

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

chai はプラグインで機能を拡張できます。例えば、非同期テスト用プラグインなどがあります。

// chai: setup

import chai from 'chai';
import chaiHttp from 'chai-http';
chai.use(chaiHttp);

jasminejasmine.json で設定します。シンプルですが、柔軟性は mocha ほど高くありません。

// jasmine: jasmine.json

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

sinon は設定というより、導入方法に注意が必要です。バンドルツールとの相性を確認します。

// sinon: webpack config

// Often requires specific loader configuration
// to mock global objects correctly

📊 機能比較まとめ

機能jestmochachaijasminesinon
テストランナー✅ 内蔵✅ 内蔵❌ 不要✅ 内蔵❌ 不要
断言ライブラリ✅ 内蔵⚠️ 別途必要✅ 専門✅ 内蔵⚠️ 検証用
モック機能✅ 内蔵⚠️ 別途必要❌ 別途必要✅ 内蔵✅ 専門
設定の手間🟢 少ない🟡 普通🟢 少ない🟢 少ない🟡 普通
主な用途React/全般Node/柔軟性断言特化単独動作モック特化

💡 最終的な選び方

jest は、特に React やフロントエンド開発において、最もバランスの取れた選択肢です。設定の手間が少なく、機能も充実しているため、迷ったらこれを選ぶのが安全です。

mocha + chai + sinon の組み合わせは、設定を細かく制御したい場合や、Node.js バックエンドなど、jest の前提条件に合わない環境で選ばれます。自由度が高い分、初期設定の手間は増えます。

jasmine は、外部ツールに依存せず、単独で完結させたい場合に適しています。レガシープロジェクトや、シンプルな環境でよく見られます。

sinon は、jestmocha だけでは足りない高度なモック機能が必要な時に追加で導入します。

テストツールは一度選ぶと変更が手間になるため、プロジェクトの規模とチームの習熟度を考慮して選定してください。

選び方: chai vs jasmine vs jest vs mocha vs sinon

  • chai:

    mocha と組み合わせて使う場合に選びます。自然言語に近い断言構文(expect/should)を使いたいプロジェクトや、既存の mocha 環境でアサーションライブラリだけを入れ替えたい時に適しています。

  • jasmine:

    外部依存なしで単独動作させる必要がある場合に適しています。設定ファイルを最小限に抑えたい単純なプロジェクトや、ブラウザ環境で直接読み込んで動かしたい時に使われます。

  • jest:

    React 系プロジェクトで、設定なしですぐ始めたい場合に最適です。スナップショットテストや並列実行など、モダンな機能が最初から揃っており、大規模なフロントエンド開発で標準的に選ばれます。

  • mocha:

    実行環境や設定を細かく制御したい場合に選ばれます。Node.js バックエンドや、特定のブラウザ設定が必要な場合など、テストランナーの挙動を自由にカスタマイズしたいプロジェクトに向いています。

  • sinon:

    jest 以外の環境で、高度なモックやスタブが必要な時に使います。mocha や chai と組み合わせて使うのが一般的で、複雑な依存関係の偽装やタイマー操作が必要な場合に威力を発揮します。

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