jest、mocha、chai、jasmine、sinon は、JavaScript アプリケーションのテストを書くために使われる主要なツールです。jest と jasmine はテスト実行から断言まで一通り揃ったフレームワークです。mocha はテスト実行に特化し、chai は断言、sinon はモック作成に特化したライブラリです。プロジェクトの規模や要件に合わせて、これらを単独または組み合わせて使用します。
jest、mocha、chai、jasmine、sinon は、JavaScript のテスト環境を構成する代表的なツール群です。これらはそれぞれ役割が異なり、単独で使うものもあれば、組み合わせて使うものもあります。開発者が最初に直面するのは「どれを組み合わせればいいか」という疑問です。ここでは、実際のコード書きながら、各ツールの役割と違いを明確にします。
テストを書くには、テストファイルを発見し、実行し、結果を報告する「テストランナー」が必要です。
jest はテストランナーを内蔵しています。ファイル名が *.test.js なら自動で検出します。
// jest: test.js
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
mocha もテストランナーですが、設定が必要です。describe と it を使います。
// 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
テストが成功したか失敗したかを判定するのが「断言」です。各ツールで書き方が異なります。
jest は expect 関数を使います。チェーン構文で読みやすく書けます。
// 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 は自然言語に近い構文が特徴です。expect、should、assert の 3 種類から選べます。
// chai
import { expect } from 'chai';
const value = 2 + 2;
expect(value).to.equal(4);
jasmine も expect を使いますが、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
jasmine は spyOn を使います。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);
jasmine は jasmine.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
| 機能 | jest | mocha | chai | jasmine | sinon |
|---|---|---|---|---|---|
| テストランナー | ✅ 内蔵 | ✅ 内蔵 | ❌ 不要 | ✅ 内蔵 | ❌ 不要 |
| 断言ライブラリ | ✅ 内蔵 | ⚠️ 別途必要 | ✅ 専門 | ✅ 内蔵 | ⚠️ 検証用 |
| モック機能 | ✅ 内蔵 | ⚠️ 別途必要 | ❌ 別途必要 | ✅ 内蔵 | ✅ 専門 |
| 設定の手間 | 🟢 少ない | 🟡 普通 | 🟢 少ない | 🟢 少ない | 🟡 普通 |
| 主な用途 | React/全般 | Node/柔軟性 | 断言特化 | 単独動作 | モック特化 |
jest は、特に React やフロントエンド開発において、最もバランスの取れた選択肢です。設定の手間が少なく、機能も充実しているため、迷ったらこれを選ぶのが安全です。
mocha + chai + sinon の組み合わせは、設定を細かく制御したい場合や、Node.js バックエンドなど、jest の前提条件に合わない環境で選ばれます。自由度が高い分、初期設定の手間は増えます。
jasmine は、外部ツールに依存せず、単独で完結させたい場合に適しています。レガシープロジェクトや、シンプルな環境でよく見られます。
sinon は、jest や mocha だけでは足りない高度なモック機能が必要な時に追加で導入します。
テストツールは一度選ぶと変更が手間になるため、プロジェクトの規模とチームの習熟度を考慮して選定してください。
mocha と組み合わせて使う場合に選びます。自然言語に近い断言構文(expect/should)を使いたいプロジェクトや、既存の mocha 環境でアサーションライブラリだけを入れ替えたい時に適しています。
外部依存なしで単独動作させる必要がある場合に適しています。設定ファイルを最小限に抑えたい単純なプロジェクトや、ブラウザ環境で直接読み込んで動かしたい時に使われます。
React 系プロジェクトで、設定なしですぐ始めたい場合に最適です。スナップショットテストや並列実行など、モダンな機能が最初から揃っており、大規模なフロントエンド開発で標準的に選ばれます。
実行環境や設定を細かく制御したい場合に選ばれます。Node.js バックエンドや、特定のブラウザ設定が必要な場合など、テストランナーの挙動を自由にカスタマイズしたいプロジェクトに向いています。
jest 以外の環境で、高度なモックやスタブが必要な時に使います。mocha や chai と組み合わせて使うのが一般的で、複雑な依存関係の偽装やタイマー操作が必要な場合に威力を発揮します。
Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
For more information or to download plugins, view the documentation.
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.
chai is available on npm. To install it, type:
$ npm install --save-dev chai
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>
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
import 'chai/register-assert'; // Using Assert style
import 'chai/register-expect'; // Using Expect style
import 'chai/register-should'; // Using Should style
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
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.
Chai offers a robust Plugin architecture for extending Chai's assertions and interfaces.
chai-pluginbrowser if your plugin works in the browser as well as Node.jsbrowser-only if your plugin does not work with Node.jsError constructor thrown upon an assertion failing.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:
chai.js build. We do it once per release.Please see the full Contributors Graph for our list of 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.
This project would not be what it is without the contributions from our prior core contributors, for whom we are forever grateful: