Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!