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.
Get hands-on with 1400+ tech skills courses.