Mocha هو إطار اختبار جافا سكريبت غني بالميزات يعمل على Node.js وفي المتصفح، مما يجعل الاختبارات غير المتزامنة بسيطة وممتعة.
واجهة التطوير الموجه بالسلوك (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)
الوعود و 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 السريع (Chai Assertions)
// أسلوب 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);