Test a Function Throwing Error
Learn to create a test that captures when a function throws.
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
text
isnull
orundefined
. - The input
text
is a non-string value object, number, and so on. - The input
n
isnull
orundefined
. - The input
n
is a non-numeric value. - The input
n
is a non-positive value.
These are expected conditions that break the function’s expectations. Namely, to slice a string, it needs an actual
string and an actual
positive number of characters to take from the start. So, the code should assert that the expectations hold before running the test.
The function expects the following parameters:
- text, which is the string to shorten.
- n, which is the count of characters to take from the start.
Let’s look into their exception cases.
An exception here means an expected but exceptional case that the function can’t deal with. It throws that further up the call ...