3

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?

tombraider
  • 1,127
  • 1
  • 11
  • 19

1 Answers1

16

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Of course! All working as expected now. Thank you for the informative answer and code snippet; I understand why the issue occured and your solution is working perfectly. – tombraider Nov 10 '16 at 14:30