Mocha は、Node.jsおよびブラウザで動作する多機能なJavaScriptテストフレームワークであり、非同期テストをシンプルに記述できます。
BDD インターフェース(BDD Interface)
const { expect } = require('chai');
describe('User Authentication', () => {
before(() => {
// このブロック内の全テストの前に1回実行
});
after(() => {
// このブロック内の全テストの後に1回実行
});
beforeEach(() => {
// 各テストの実行前に毎回実行
});
afterEach(() => {
// 各テストの実行後に毎回実行
});
it('should authenticate user with valid credentials', () => {
const user = authenticate('[email protected]', 'secret');
expect(user).to.be.an('object');
expect(user.token).to.be.a('string');
});
it.skip('temporarily skipped test', () => {
// このテストの実行を一時的にスキップ
});
});
非同期テスト(Asynchronous Tests)
Promise と Async/Await
it('should fetch user profile from API', async () => {
const profile = await fetchProfile(101);
expect(profile.name).to.equal('Alice');
});
done() コールバック関数
it('should save document via callback', (done) => {
document.save((err) => {
if (err) return done(err);
done();
});
});
Chai アサーション クイックガイド
// Should スタイル
chai.should();
user.should.have.property('name').equal('Alice');
list.should.have.lengthOf(3);
// Expect スタイル
expect(user).to.be.an('object');
expect(list).to.include(42);