【初心者向け】MochaとChaiを使ってPromiseをテストするステップバイステップガイド
MochaとChaiを使ってPromiseをテストする方法
chai-as-promisedのインストール
まず、chai-as-promised
というChaiプラグインをインストールする必要があります。これは、Promiseに関する追加のアサーションを提供します。
npm install chai-as-promised
テストの記述
以下の例は、getUserById
という非同期関数があると仮定します。この関数は、IDに基づいてユーザー情報を返すPromiseを返します。
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const { expect } = chai;
const getUserById = require('./getUserById');
chai.use(chaiAsPromised);
describe('getUserById', () => {
it('should return user with given ID', async () => {
const userId = 123;
const user = await getUserById(userId);
expect(user).to.have.property('id', userId);
expect(user).to.have.property('name', 'John Doe');
});
it('should reject with error if user not found', async () => {
const nonExistentUserId = 456;
await expect(getUserById(nonExistentUserId)).to.be.rejectedWith('User not found');
});
});
この例では、以下の点に注目してください。
describe
とit
を使ってテストを記述しています。await
を使って非同期処理を待機しています。expect
を使ってPromiseの結果を検証しています。chai-as-promised
の提供するアサーションを使って、Promiseが解決されるか拒否されるかを検証しています。
テストを実行するには、以下のコマンドを実行します。
mocha
補足
- Mochaは、done callbackを使ってPromiseをテストすることもできますが、これは非推奨です。
- テスト駆動開発 (TDD) の手法を使って、Promiseを使ったコードをテストすることができます。
サンプルコード:非同期APIをモックする
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const { expect } = chai;
const sinon = require('sinon');
const getUserById = require('./getUserById');
chai.use(chaiAsPromised);
describe('getUserById', () => {
beforeEach(() => {
sinon.stub(getUserById, 'fetchUserFromAPI').resolves({
id: 123,
name: 'John Doe',
});
});
afterEach(() => {
getUserById.fetchUserFromAPI.restore();
});
it('should return user with given ID', async () => {
const userId = 123;
const user = await getUserById(userId);
expect(user).to.have.property('id', userId);
expect(user).to.have.property('name', 'John Doe');
});
});
sinon
ライブラリを使って、getUserById
関数のfetchUserFromAPI
メソッドをモックしています。beforeEach
とafterEach
を使って、モックをセットアップとクリーンアップしています。- モックされた
fetchUserFromAPI
メソッドは、常に成功し、固定のユーザーオブジェクトを返します。 - テストは、モックされたAPIが期待通りに動作することを検証します。
MochaとChaiを使ってPromiseをテストするその他の方法
done コールバックを使用する
これは、MochaでPromiseをテストする古い方法です。しかし、非推奨であり、避けるべきです。
const chai = require('chai');
const assert = chai.assert;
const getUserById = require('./getUserById');
describe('getUserById', () => {
it('should return user with given ID', (done) => {
const userId = 123;
getUserById(userId, (err, user) => {
if (err) {
done(err);
return;
}
assert.equal(user.id, userId);
assert.equal(user.name, 'John Doe');
done();
});
});
});
- テストは
done
コールバックを受け取ります。 - 非同期処理が完了したら、
done
コールバックを呼び出す必要があります。 - アサーションは、
done
コールバックが呼び出される前に実行する必要があります。
async/awaitを使用する
これは、MochaでPromiseをテストするより現代的な方法です。
const chai = require('chai');
const { expect } = chai;
const getUserById = require('./getUserById');
chai.use(chaiAsPromised);
describe('getUserById', () => {
it('should return user with given ID', async () => {
const userId = 123;
const user = await getUserById(userId);
expect(user).to.have.property('id', userId);
expect(user).to.have.property('name', 'John Doe');
});
});
- テストは
async
キーワードでマークされています。
どの方法を使用するかは、個人の好みとテストの要件によって異なります。しかし、一般的には、async/await
を使用する方法の方が、簡潔で読みやすく、メンテナンスしやすいことをお勧めします。
node.js promise mocha.js