DEV Community

Cover image for Testing errors with Jest
Dany Paredes
Dany Paredes

Posted on

Testing errors with Jest

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 lest to edit the calculator class and add the following steps.

  • Define array with the list of valid action.
  • If the Action is not into the array throw an error.

Your code will look like:

export class Calculator {
    static validActions: Array<string> = ['+',"-","/"];
    public static increase(value: number) {
        return value + 1;
    public static generateCalcSetting(valueA: number, action: string, valueB: number) {

            throw new Error("Invalid action");

        let result : number;
        switch (action) {
            case "+":
                result = valueA + valueB;
            case "-":
                result = valueA - valueB;
            case "/":
                result = valueA / valueB;
                result = 0;

        return  {
            mathAction: action,

Enter fullscreen mode Exit fullscreen mode

Perfect, update the Calculator.test.ts and use jest matchers toBeInstanceOf() it helps to get the type, so we need to do the following changes.

  • Use try catch statement.
  • call the generateCalcSettings with wrong parameters
  • The catch take the return and use tobeInstanceOf and compare 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 {
        } catch (error) {
            expect(error.message).toBe('Invalid action');

Enter fullscreen mode Exit fullscreen mode

Run our tests and get the results

dany@dany:~/Desktop/calculator(master)$ npm run test

> calculator@1.0.0 test /home/dany/Desktop/calculator
> jest

 PASS  src/tests/Calculator.test.ts
    ✓ should return a number (1 ms)
    ✓ should increment the number (1 ms)
    ✓ should return a calculation Object logic (1 ms)
    ✓ should return a error if is invalid action (1 ms)

Test Suites: 1 passed, 1 total
Tests:       4 passed, 4 total
Snapshots:   0 total
Time:        2.253 s
Ran all test suites.
Enter fullscreen mode Exit fullscreen mode

Great! The matcher toBeInstanceOf allow to get the error type and also read the properties message to validate the error message is the expected.

Photo by Sarah Kilian on Unsplash

Top comments (0)