Mocha offre diverse interfacce di test. Mentre bdd usa describe() e it(), l’interfaccia tdd adotta le convenzioni classiche in stile xUnit con suite() e test().
Configurazione Interfaccia TDD
const { expect } = require('chai');
// Configura Mocha per usare l’interfaccia TDD
mocha.setup('tdd');
suite('Payment Processing', () => {
suiteSetup(() => {
// Viene eseguito una volta prima di tutti i test in questa suite
});
suiteTeardown(() => {
// Viene eseguito una volta dopo tutti i test in questa suite
});
setup(() => {
// Viene eseguito prima di ogni test
});
teardown(() => {
// Viene eseguito dopo ogni test
});
test('validates card expiration date', () => {
const isValid = validateExpiry('12/28');
expect(isValid).to.be.true;
});
test('handles async network payments', async () => {
const receipt = await chargeCard(100);
expect(receipt.status).to.equal('success');
});
});
Confronto: BDD vs TDD
| Concetto | Interfaccia BDD (bdd) |
Interfaccia TDD (tdd) |
|---|---|---|
| Gruppo di Test | describe("name", () => {}) |
suite("name", () => {}) |
| Singolo Test | it("does something", () => {}) |
test("does something", () => {}) |
| Hook Prima di Tutti | before(() => {}) |
suiteSetup(() => {}) |
| Hook Dopo Tutti | after(() => {}) |
suiteTeardown(() => {}) |
| Hook Prima di Ogni Test | beforeEach(() => {}) |
setup(() => {}) |
| Hook Dopo Ogni Test | afterEach(() => {}) |
teardown(() => {}) |
Esecuzione Test TDD via CLI
Di default la CLI di Mocha utilizza l’interfaccia BDD. Per eseguire suite TDD, specifica --ui tdd:
mocha --ui tdd test/tdd/*.test.js