Dany Paredes
Dany Paredes | Javascript / Web

Dany Paredes | Javascript / Web

How test errors with Jest in Javascript

Photo by Markus Spiske on Unsplash

How test errors with Jest in Javascript

Use Jest to test errors in your code

Dany Paredes's photo
Dany Paredes
·Jan 23, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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 actions.
  • 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) {

        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 do the following changes.

  • Use try catch statement.
  • call the generateCalcSettings with the wrong parameters
  • The catch takes the return and 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 the error message is expected.

 
Share this