Mocha est un framework de test JavaScript complet pour Node.js et navigateurs, rendant les tests asynchrones simples et robustes.
Interface BDD (BDD Interface)
const { expect } = require('chai');
describe('User Authentication', () => {
before(() => {
// S'execute une fois avant tous les tests du bloc
});
after(() => {
// S'execute une fois apres tous les tests du bloc
});
beforeEach(() => {
// S'execute avant chaque test individuel
});
afterEach(() => {
// S'execute apres chaque test individuel
});
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', () => {
// Ignore temporairement l'execution de ce test
});
});
Tests asynchrones (Asynchronous Tests)
Promesses et Async/Await
it('should fetch user profile from API', async () => {
const profile = await fetchProfile(101);
expect(profile.name).to.equal('Alice');
});
Rappels avec done()
it('should save document via callback', (done) => {
document.save((err) => {
if (err) return done(err);
done();
});
});
Guide rapide des assertions Chai
// Style Should
chai.should();
user.should.have.property('name').equal('Alice');
list.should.have.lengthOf(3);
// Style Expect
expect(user).to.be.an('object');
expect(list).to.include(42);