How can I write a test which expects an 'Error' to be thrown in Jasmine?
For a quick error expectation in Jasmine, make use of toThrowError()
chained with expect
where the function is wrapped in an arrow function:
This simply tests that the function myFunctionThatShouldThrow
throws an error when called. You may modify the .toThrowError()
to suit your test case for different Error types or messages.
Digging Deeper: Probing Specific Exceptions
When tests get more complex, here are a few error scenarios you might encounter:
1. Checking for Precise Error Messages
If you're looking for specific error messages, this is your magic wand:
2. Error Type Expectation
What's the type of the error? TypeError
? RangeError
? toThrowErrorOfType
has got you covered:
3. Advanced Error Testing with Jasmine Matchers
If your test cases are as complex as quantum physics, then Jasmine-Matchers might be a good friend:
4. Custom Expectations with Custom Matchers
In need of custom expectations? Jasmine allows for tasty homemade custom matchers note for your exceptional situations.
Context Management: ES5's bind
to the Rescue
When functions need a certain context or pre-set arguments, the bind
can be very helpful:
Nuanced Approach in Excellence
1. Sturdy Tests: Exception Types Over Messages
Assert the type of exception rather than the specific messages—a change in messages shouldn't break the titanium of your tests!
2. Syntax Decisions: ES5 vs ES6
Know which battlefield you're in—ES5 or ES6—your syntax for defining the test functions may differ (function()
vs arrow () =>
).
Best Practices: Striving for Mastery
1. Giving the Correct Function a Swing
Make sure you're swinging at the right function in your test:
2. Strings and Error Messages: Perfect Marriage
Don't forget, your specific error messages should always be dressed in strings when in toThrowError
.
3. Elegance Personified: Preparing your Function Call
Ever heard of dressing up before the party? Do the same with your function call:
Was this article helpful?