How to test throw with Jest


Table of contents


Assumptions

  • You know how to install and use Jest
  • You know how to develop programs in JavaScript


Resources

  • The Jest documentation.


Scenario

Currently, at work, there is an effort to refactor a codebase to make it more maintainable and scalable. The JavaScript code is running in an unusual environment that is not a browser nither a node server. I’m extracting common functionality into a utility library and writing unit-test for all functions.
I have used Jest before for frontend code but this is the first time using Jest for pure functions. Our use case is particular and we need to carefully choose which functions are going to throw/return an error.
When I start writing unit-test for a function that returns an error I started having issues with it. Let consider a sample function and let’s say that I’m going to throw an error if any of the parameters are null.

function addTwoNumbers(num1, num2) {
    const num1IsNull = num1 === null
    const num2IsNull = num2 === null

    if (num1IsNull || num2IsNull) {
        throw 'One of the parameters is not a number'
    }
    ... // continue your code
}

// testing

const addTwoNumbers = require('path/to/addTwoNumbers')

describe('addTwoNumbers', () => {
    it('should throw error if num1 is null', () => {
        // This expect wont error out but it wont pass either.
        expect(addTwoNumbers(null, 2)).toBe("One of the parameters is not a number")
    })
})


The correct way to test this is not by expecting the string that comes back but rather that the function did throw. Let’s consider the following test. It will be slightly different from the above.

const addTwoNumbers = require('path/to/addTwoNumbers')

describe('addTwoNumbers', () => {
    it('should throw error if num1 is null', () => {
        // Notice that expect takes a function that return the function under test. 
        // If I pass (3,5) the test will faild.
        expect(() => addTwoNumbers(null, 2)).toThrow()
    })
})