Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chai - expect function to throw error [duplicate]

I'm quite new to Chai so I'm still getting to grips with things.

I have written function that will check an API response and return either the correct messaging or throw an error.

networkDataHelper.prototype.formatPostcodeStatus = function(postcodeStatus) {

if (postcodeStatus.hasOwnProperty("errorCode")) {
    //errorCode should always be "INVALID_POSTCODE"
    throw Error(postcodeStatus.errorCode);
}

if (postcodeStatus.hasOwnProperty("lori")) {
    return "There appears to be a problem in your area. " + postcodeStatus.lori.message;
}

else if (postcodeStatus.maintenance !== null) {
    return postcodeStatus.maintenance.bodytext;
}

else {
    return "There are currently no outages in your area.";
}
};

I've managed to write tests for the messaging, however, I'm struggling with the error test. Here's what I've written to date:

var networkDataHelper = require('../network_data_helper.js');

describe('networkDataHelper', function() {
var subject = new networkDataHelper();
var postcode;

    describe('#formatPostcodeStatus', function() {
        var status = {
            "locationValue":"SL66DY",
            "error":false,
            "maintenance":null,
        };

        context('a request with an incorrect postcode', function() {
            it('throws an error', function() {
                status.errorCode = "INVALID_POSTCODE";
                expect(subject.formatPostcodeStatus(status)).to.throw(Error);
            });
        });
    });
});

When I run the test above, I get the following error message:

1) networkDataHelper #formatPostcodeStatus a request with an incorrect postcode throws an error: Error: INVALID_POSTCODE

It seems like the error that is being thrown is causing the test to fail, but I'm not too sure. Does anyone have any ideas?

like image 695
tombraider Avatar asked Nov 15 '25 23:11

tombraider


1 Answers

With the caveat that I'm no Chai expert, the construct you have:

expect(subject.formatPostcodeStatus(status)).to.throw(Error);

cannot possibly handle the thrown exception before the Chai framework gets around to seeing your .to.throw() chain. The code above calls the function before the call to expect() is made, so the exception happens too soon.

Instead, you should pass a function to expect():

expect(function() { subject.formatPostCodeStatus(status); })
  .to.throw(Error);

That way, the framework can invoke the function after it's prepared for the exception.

like image 164
Pointy Avatar answered Nov 18 '25 12:11

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!