Mocha — гибкий и многофункциональный тестовый фреймворк для 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)
Промисы и 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);