Mocha is een veelzijdig JavaScript-testframework voor Node.js en browsers dat asynchrone tests eenvoudig en krachtig maakt.
BDD-interface (BDD Interface)
const { expect } = require('chai');
describe('User Authentication', () => {
before(() => {
// Voert eenmaal uit voor alle tests in dit blok
});
after(() => {
// Voert eenmaal uit na alle tests in dit blok
});
beforeEach(() => {
// Voert uit voor elke afzonderlijke test
});
afterEach(() => {
// Voert uit na elke afzonderlijke test
});
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', () => {
// Slaat de uitvoering van deze test over
});
});
Asynchrone tests (Asynchronous Tests)
Promises en Async/Await
it('should fetch user profile from API', async () => {
const profile = await fetchProfile(101);
expect(profile.name).to.equal('Alice');
});
Callbacks met done()
it('should save document via callback', (done) => {
document.save((err) => {
if (err) return done(err);
done();
});
});
Chai Asserties Korte Handleiding
// Should-stijl
chai.should();
user.should.have.property('name').equal('Alice');
list.should.have.lengthOf(3);
// Expect-stijl
expect(user).to.be.an('object');
expect(list).to.include(42);