Unit Test - How to check for an expected error?

1

In a unit test for a module using Mocha and Chai , I 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 actual 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 looks 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"');
  });
});

However with the above test the test fails when in fact the expected error is displayed. How can I correctly test the expected result for the error of an asynchronous function?

    
asked by anonymous 01.08.2018 / 04:21

1 answer

1

Based on a Chai issue ( link ) 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);
  });

});
    
01.08.2018 / 04:40