Jasmine: trapping thrown errors

This is WAY easier than trapping a specific exception in C#:

Test – note that to get the test to pass, you (seem to) have to pass an anonymous function to expect():

CatchExceptions01

Being new-ish to JavaScript, the specifics are new, but the concepts obviously/hopefully aren’t . So if the argument passed is NotANumber, then we’ll throw a custom exception. For all I know this may somehow not be best practice… but it works for my purposes right now:

CatchExceptions02

And then the happy path test – I love the sensible idea of toBeCloseTo – I haven’t looked at its tolerances but what a great idea when “Close Enough” is all you want:

CatchExceptions03

CatchExceptions04

And this Jasmine cheatsheet is pretty useful.

it(“should only accept numbers when converting pounds to kilos”,function() {
expect(function() { ctrl.convertPoundsToKilos(“aa”); }).
toThrow(new Error(“the value was not a number”));
});

it(“should convert pounds to kilos”,function() {
expect(ctrl.convertPoundsToKilos(22)).toBeCloseTo(9.98);
});

vm.convertPoundsToKilos = function(weightInPounds) {
if (isNaN(weightInPounds)) {
throw new Error(“the value was not a number”);
};

return weightInPounds / 2.204623;
};

Did some more on Plunker – worth digesting for the dependency chain:

http://plnkr.co/edit/SOnuRBENH4jWS0BV0zLi?p=preview

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s