Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
How to test error handling functions in Javascript

I m trying to write unit test cases to handle error codes that are defined below. not sure how to achieve it.

module.exports = {
    Error: Err,
    BadRequest: function () {
        return new Err(400, 'Bad Request');
    },
    NotAcceptable: function () {
        return new Err(406, 'Not Acceptable');
    },
    NotAuthorized: function () {
        return new Err(401, 'Not Authorized');
    }
};

function Err(code, message) {
    assert(code, 'code');

    Error.call(this);
    Error.captureStackTrace(this, this.constructor);

    Object.defineProperty(this, 'code', {
        enumerable: true,
        value: code
    });

    this.reason = message;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should have a better base error layer by extending the Error class which already provide most of the functions you would need (capturing the stack trace automatically):

class Err extends Error {
    constructor(code, message) {
        super(message);
        this.code = code;
        this.reason = message;
    }
}

You can then performa your assertion using the throw expectation:

const errorFn = () => { throw new Err(401, 'Unauthorized') };

expect(errorFn).to.throw(Err).to.haveOwnProperty('code', 401).to.haveOwnProperty('reason', 'Unauthorized');

You should obviously update your sub-error accordingly to extend your generic error.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda