Riferimento rapido

Foglio di riferimento Mocha.js BDD

Guida rapida di riferimento per Mocha.js: interfaccia di test BDD, describe, it, hook di ciclo di vita, test asincroni e asserzioni Chai.

· Pubblicato

Mocha e un ricco framework di test JavaScript per Node.js e browser, che rende il testing asincrono semplice ed efficace.

Interfaccia BDD (BDD Interface)

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

describe('User Authentication', () => {
  before(() => {
    // Viene eseguito una sola volta prima di tutti i test
  });

  after(() => {
    // Viene eseguito una sola volta dopo tutti i test
  });

  beforeEach(() => {
    // Viene eseguito prima di ogni singolo test
  });

  afterEach(() => {
    // Viene eseguito dopo ogni singolo 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', () => {
    // Salta temporaneamente l'esecuzione di questo test
  });
});

Test asincroni (Asynchronous Tests)

Promise e Async/Await

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

Callback con done()

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

Guida rapida asserzioni Chai

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

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

Riferimenti correlati

Argomenti correlati