Mocha udostępnia wiele interfejsów testowania. Podczas gdy bdd używa describe() oraz it(), interfejs tdd stosuje klasyczną konwencję xUnit z suite() i test().
Konfiguracja interfejsu TDD
const { expect } = require('chai');
// Skonfiguruj Mocha do pracy z interfejsem TDD
mocha.setup('tdd');
suite('Payment Processing', () => {
suiteSetup(() => {
// Uruchamiany raz przed wszystkimi testami w tej grupie
});
suiteTeardown(() => {
// Uruchamiany raz po wszystkich testach w tej grupie
});
setup(() => {
// Uruchamiany przed każdym testem
});
teardown(() => {
// Uruchamiany po każdym teście
});
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');
});
});
Porównanie: BDD vs TDD
| Pojęcie | Interfejs BDD (bdd) |
Interfejs TDD (tdd) |
|---|---|---|
| Grupa testów | describe("name", () => {}) |
suite("name", () => {}) |
| Pojedynczy test | it("does something", () => {}) |
test("does something", () => {}) |
| Hook przed wszystkimi | before(() => {}) |
suiteSetup(() => {}) |
| Hook po wszystkich | after(() => {}) |
suiteTeardown(() => {}) |
| Hook przed każdym testem | beforeEach(() => {}) |
setup(() => {}) |
| Hook po każdym teście | afterEach(() => {}) |
teardown(() => {}) |
Uruchamianie testów TDD przez CLI
Domyślnie Mocha CLI korzysta z interfejsu BDD. Aby uruchomić zestawy TDD, podaj --ui tdd:
mocha --ui tdd test/tdd/*.test.js