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?