Kurzreferenz

Mocha.js BDD Test-Framework Spickzettel

Kurzreferenz fuer Mocha.js: BDD-Testsuite-Schnittstelle, describe, it, Hooks, asynchrone Tests und Chai-Assertions.

· Veröffentlicht

Mocha ist ein funktionsreiches JavaScript-Testframework fuer Node.js und Browser, das asynchrone Tests einfach und uebersichtlich macht.

BDD-Schnittstelle (BDD Interface)

const { expect } = require('chai');

describe('User Authentication', () => {
  before(() => {
    // Laeuft einmal vor allen Tests in diesem Block
  });

  after(() => {
    // Laeuft einmal nach allen Tests in diesem Block
  });

  beforeEach(() => {
    // Laeuft vor jedem einzelnen Test
  });

  afterEach(() => {
    // Laeuft nach jedem einzelnen Test
  });

  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', () => {
    // Ueberspringt die Ausfuehrung dieses Tests
  });
});

Asynchrone Tests (Asynchronous Tests)

Promises und Async/Await

it('should fetch user profile from API', async () => {
  const profile = await fetchProfile(101);
  expect(profile.name).to.equal('Alice');
});

Callbacks mit done()

it('should save document via callback', (done) => {
  document.save((err) => {
    if (err) return done(err);
    done();
  });
});

Chai-Assertions Kurzreferenz

// Should-Stil
chai.should();
user.should.have.property('name').equal('Alice');
list.should.have.lengthOf(3);

// Expect-Stil
expect(user).to.be.an('object');
expect(list).to.include(42);

Verwandte Referenzen

Verwandte Themen