Unit Test - How to verify an expected error?

Asked

Viewed 183 times

1

In a unit test for a module using Mocha and Chai need to check if an error is returned if the parameter format is invalid.

The function of the module in question returns a Promise.

The example below is fictitious but has the result of the real problem.

const FORMATO_PLACA = /^[a-zA-Z]{3}[0-9]{4}$/gim;
const ESPECIAIS     = /[^a-zA-Z0-9]/gi;

async function validar(placa) {
  placa = placa.replace(ESPECIAIS, '');

  if (!FORMATO_PLACA.test(placa)) {
    throw new Error('Formato de placa inválido! Utilize o formato "AAA999" ou "AAA-9999".');
  }

  return placa;
}

module.exports = {validar};

And the test code is something like:

const modulo = require('../modulo');
const chai   = require('chai');
const path   = require('path');

const expect  = chai.expect;

describe('validar', function() {
  it('Falhar ao informar um formato inválido', async function() {
    return expect(await modulo.validar('AAAAAAA')).to.throw('Formato de placa inválido! Utilize o formato "AAA999" ou "AAA-9999"');
  });
});

But with the above test the test fails when in reality the expected error is presented. How can I correctly test the expected result for an asynchronous function error?

1 answer

1


Based on an Issue in Chai (https://github.com/chaijs/chai/issues/415) follows the solution:

const modulo = require('../modulo');
const chai   = require('chai');
const chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);

const expect  = chai.expect;

describe('validar', function() {
  it.only('Falhar ao informar um formato inválido', function() {
    return expect(modulo.validar('AAAAAAA')).to.be.rejectedWith(Error);
  });

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.