How to Test Errors with Jest in Typescript

I'm continuing with Jest and typescript, we already know how to expect and assert variables and objects in our code, next step is handling errors.
The Calculator has a new requirement if the type of calculation is not +,- or / we need to throw an error.
The test is to edit the calculator class and add the following steps.
-
Define array with the list of valid actions.
-
If the Action is not in the array throw an error.
Your code will look like this:
export class Calculator {
static validActions: Array<string> = ['+',"-","/"];
public static increase(value: number) {
return value + 1;
}
public static generateCalcSetting(valueA: number, action: string, valueB: number) {
if(!this.validActions.includes(action)){
throw new Error("Invalid action");
}
let result : number;
switch (action) {
case "+":
result = valueA + valueB;
break;
case "-":
result = valueA - valueB;
break;
case "/":
result = valueA / valueB;
default:
result = 0;
}
return {
valueA,
mathAction: action,
valueB,
result
}
}
}Perfect, create the Calculator.test.ts file and use jest matchers toBeInstanceOf() it helps to get the type, so we need to make the following changes.
-
Use a try-catch statement.
-
call the generateCalcSettings with the wrong parameters
-
The catch takes the return uses tobeInstanceOf and compares with type Error.
-
compare the error.message toBe ('Invalid action')
Your code should look like:
it('should return a error if is invalid action',() => {
try {
Calculator.generateCalcSetting(1,'M',5);
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error.message).toBe('Invalid action');
}
})Run our tests and get the results
npm run test
> calculator@1.0.0 test /home/dany/Desktop/calculator
> jest
PASS src/tests/Calculator.test.ts
Calculator
✓ should return an error if is invalid action (1 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.253 s
Ran all test suites.Great! The matcher toBeInstanceOf allows us to get the error type and also read the properties message to validate that the error message is expected.
Nice!
Related Articles
How To Mock Dependencies With Jest
When we want to test our code, some things have dependencies inside, and you don't want to call this stuff. You won't be sure your code works, not external dependencies or external code unrelated to my code. Today we will add tests to our example wea...
Using Class Decorators in Typescript with a real example
The Decorators are an excellent Typescript feature; maybe you see them all over Angular and other frameworks. It helps to write code clean and declarative, maybe you already use it every day, but do you know when to create your decorators? I will s...
Real Software. Real Lessons.
I share the lessons I learned the hard way, so you can either avoid them or be ready when they happen.
Join 13,800+ developers and readers.
No spam ever. Unsubscribe at any time.