javascript - Chai - expect function to throw error -
this question has answer here:
i'm quite new chai i'm still getting grips things.
i have written function check api response , return either correct messaging or throw error.
networkdatahelper.prototype.formatpostcodestatus = function(postcodestatus) { if (postcodestatus.hasownproperty("errorcode")) { //errorcode should "invalid_postcode" throw error(postcodestatus.errorcode); } if (postcodestatus.hasownproperty("lori")) { return "there appears problem in area. " + postcodestatus.lori.message; } else if (postcodestatus.maintenance !== null) { return postcodestatus.maintenance.bodytext; } else { return "there no outages in area."; } };
i've managed write tests messaging, however, i'm struggling error test. here's i've written 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 incorrect postcode', function() { it('throws error', function() { status.errorcode = "invalid_postcode"; expect(subject.formatpostcodestatus(status)).to.throw(error); }); }); }); });
when run test above, following error message:
1) networkdatahelper #formatpostcodestatus request incorrect postcode throws error: error: invalid_postcode
it seems error being thrown causing test fail, i'm not sure. have ideas?
with caveat i'm no chai expert, construct have:
expect(subject.formatpostcodestatus(status)).to.throw(error);
cannot possibly handle thrown exception before chai framework gets around seeing .to.throw()
chain. code above calls function before call expect()
made, exception happens soon.
instead, should pass function expect()
:
expect(function() { subject.formatpostcodestatus(status); }) .to.throw(error);
that way, framework can invoke function after it's prepared exception.
Comments
Post a Comment