How to Test Errors with Jest in Typescript

Leverage Jest to assess errors in your Typescript development

Table of contents

No heading

No headings in the article.

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!