Mocha는 Node.js 및 브라우저에서 동작하는 풍부한 기능의 자바스크립트 테스트 프레임워크로, 비동기 테스팅을 유연하게 처리합니다.
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);