mocha-skill について
Mochaでテストを作成・実行するためのスキルガイドです。Chaiのアサーション、Sinonのモック、非同期テスト、コマンド、テスト構成を説明します。
主な機能
- 01Mochaのテスト構造とフック
- 02Chaiのアサーション
- 03Sinonのモックとサンドボックス
- 04Promiseとコールバックのテスト
- 05実行・監視・絞り込みコマンド
活用シーン
- 01JavaScriptの関数やサービスのテスト
- 02テスト中の依存関係の置き換え
- 03非同期コードやコールバックの確認
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ lambdatest/ agent-skills --skill mocha-skillインストール後、Claude Code で/mocha-skillを入力して読み込まれたか確認します。
同梱ファイルreference/advanced-patterns.mdreference/playbook.md
詳細
Mocha テストスキル
基本パターン
Chai を使った基本的なテスト
const { expect } = require('chai');
describe('Calculator', () => {
let calc;
beforeEach(() => { calc = new Calculator(); });
it('should add two numbers', () => {
expect(calc.add(2, 3)).to.equal(5);
});
it('should throw on divide by zero', () => {
expect(() => calc.divide(10, 0)).to.throw('Division by zero');
});
});
Chai アサーション
expect(value).to.equal(5);
expect(arr).to.have.lengthOf(3);
expect(obj).to.have.property('name');
expect(str).to.include('hello');
expect(fn).to.throw(Error);
expect(arr).to.deep.equal([1, 2, 3]);
expect(obj).to.deep.include({ name: 'Alice' });
Sinon によるモック
const sinon = require('sinon');
describe('UserService', () => {
let sandbox;
beforeEach(() => { sandbox = sinon.createSandbox(); });
afterEach(() => { sandbox.restore(); });
it('fetches user from API', async () => {
const stub = sandbox.stub(api, 'get').resolves({ name: 'Alice' });
const user = await userService.getUser(1);
expect(user.name).to.equal('Alice');
expect(stub.calledOnce).to.be.true;
});
});
非同期テスト
it('should fetch data', async () => {
const data = await fetchData();
expect(data).to.have.property('id');
});
it('callback style', (done) => {
fetchData((err, data) => {
expect(err).to.be.null;
done();
});
});
アンチパターン
| 悪い例 | 良い例 | 理由 |
|---|---|---|
done() がない | async/await を使う | テストが終了しない |
| サンドボックスがない | sinon.createSandbox() | スタブが漏れる |
describe でアロー関数を使う | this.timeout() には通常の関数を使う | コンテキスト |
クイックリファレンス
| タスク | コマンド |
|---|---|
| すべて実行 | npx mocha |
| 監視 | npx mocha --watch |
| 検索 | npx mocha --grep "login" |
| タイムアウト | npx mocha --timeout 10000 |
| 再帰的に実行 | npx mocha --recursive |
セットアップ:npm install mocha chai sinon --save-dev
詳細なパターン → reference/playbook.md
| § | セクション | 行 |
|---|---|---|
| 1 | 本番環境の設定 | mocharc、NYC カバレッジ、TypeScript |
| 2 | Chai + Sinon を使ったテスト | スタブ、スパイ、アサーション |
| 3 | Sinon の高度なパターン | フェイクタイマー、nock HTTP、逐次処理 |
| 4 | 非同期パターン | Promise、await、コールバック、イベント |
| 5 | フックとテストの構成 | ライフサイクル、ネスト、grep タグ |
| 6 | カスタムレポーターとプラグイン | レポータークラス、ルートフック |
| 7 | Express/API テスト | Supertest の統合 |
| 8 | CI/CD 統合 | GitHub Actions、サービス |
| 9 | デバッグのクイックリファレンス | よくある問題 10 件 |
| 10 | ベストプラクティスのチェックリスト | 13 項目 |
コメント
Markdown 対応