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?