Szybka pomoc

Ściągawka z Mocha.js BDD

Szybki przewodnik po Mocha.js: interfejs testowy BDD, describe, it, hooki cyklu życia, testy asynchroniczne i asercje Chai.

· Opublikowano

Mocha to wszechstronny framework testowy JavaScript dla Node.js i przeglądarek, upraszczający testy asynchroniczne.

Interfejs BDD (BDD Interface)

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

describe('User Authentication', () => {
  before(() => {
    // Uruchamia sie raz przed wszystkimi testami w bloku
  });

  after(() => {
    // Uruchamia sie raz po wszystkich testach w bloku
  });

  beforeEach(() => {
    // Uruchamia sie przed kazdym pojedynczym testem
  });

  afterEach(() => {
    // Uruchamia sie po kazdym pojedynczym testem
  });

  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', () => {
    // Tymczasowo pomija wykonanie testu
  });
});

Testy asynchroniczne (Asynchronous Tests)

Obietnice (Promises) i Async/Await

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

Wywołania zwrotne z done()

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

Szybki przewodnik po asercjach Chai

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

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

Powiązane materiały

Powiązane tematy