Το Mocha είναι ένα ευέλικτο πλαίσιο δοκιμών JavaScript που εκτελείται σε Node.js και στο πρόγραμμα περιήγησης.
Διεπαφή BDD (BDD Interface)
const { expect } = require('chai');
describe('User Authentication', () => {
before(() => {
// Εκτελειται μια φορα πριν απο ολες τις δοκιμες
});
after(() => {
// Εκτελειται μια φορα μετα απο ολες τις δοκιμες
});
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)
Υποσχέσεις (Promises) & Async/Await
it('should fetch user profile from API', async () => {
const profile = await fetchProfile(101);
expect(profile.name).to.equal('Alice');
});
Ανακλήσεις (Callbacks) με 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);