Test a Function Throwing Error
Explore how to create Jasmine unit tests that ensure JavaScript functions throw appropriate errors for invalid inputs. Learn to test for null, undefined, non-string, and non-numeric parameters to make your code more robust and reliable.
Throw
When a function throws as part of its logic, there should be a test case that captures that.
The function
The following function accepts a string text and a number n and returns the first n characters of the string.
function getFirstNChars(text, n) {
return text.slice(0, n);
}
The implementation uses the slice method out of the string.prototype (click here for details). It slices the passed in text from index 0 to n.
Tests
Since this lesson focuses on testing the error cases (below), first let’s try to implement this test case:
“The firsNChars function should return the first n characters from a string!”
Use src/first-n-chars.spec.js in the code playground below.
This first spec should test the intended use case, also known as the green path.
If stuck, see the hint below the code widget.
const SpecReporter = require('jasmine-spec-reporter').SpecReporter
jasmine.getEnv().clearReporters();
jasmine.getEnv().addReporter(
new SpecReporter({
// add jasmine-spec-reporter
spec: {
displayPending: false,
},
})
)
All right, that takes care of the intended use case. Congratulations on taking the time to write that test!
Incidentally, it might seem painfully obvious and redundant as a piece of code. That’s how a lot of test cases look initially. Their value becomes evident in time.
Corner cases
This implementation works but has a few issues. It doesn’t take into account the cases when:
- The input
textisnullorundefined. - The input
textis a non-string value object, number, and so on. - The input
nisnullorundefined. - The input
nis a non-numeric value. - The input
nis a non-positive value.
These are expected conditions that break the function’s expectations. Namely, ...