Jest Unit testing — Use of Matchers (Part2)
2 min readMar 21, 2021
What is matcher in Jest?
Jest uses matchers to test the unit test cases in different ways like matching the equal values, truthiness, numbers, strings, and so on.
Exceptions
// const fn = () => { throw new Error('Oops error!') }
expect(fn).toThrow()
expect(fn).toThrow('Oops error')
expect(fn).toThrowErrorMatchingSnapshot()
Snapshots
expect(node).toMatchSnapshot()
// Jest 23+
expect(user).toMatchSnapshot({
date: expect.any(Date)
})
expect(user).toMatchInlineSnapshot()
Mock functions
// const fn = jest.fn()
// const fn = jest.fn().mockName('Unicorn') -- named mock, Jest 22+
expect(fn).toBeCalled() // Function was called
expect(fn).not.toBeCalled() // Function was *not* called
expect(fn).toHaveBeenCalledTimes(1) // Function was called only once
expect(fn).toBeCalledWith(arg1, arg2) // Any of calls was with these arguments
expect(fn).toHaveBeenLastCalledWith(arg1, arg2) // Last call was with these arguments
expect(fn).toHaveBeenNthCalledWith(callNumber, args) // Nth call was with these arguments (Jest 23+)
expect(fn).toHaveReturnedTimes(2) // Function was returned without throwing an error (Jest 23+)
expect(fn).toHaveReturnedWith(value) // Function returned a value (Jest 23+)
expect(fn).toHaveLastReturnedWith(value) // Last function call returned a value (Jest 23+)
expect(fn).toHaveNthReturnedWith(value) // Nth function call returned a value (Jest 23+)
expect(fn.mock.calls).toEqual([['first', 'call', 'args'], ['second', 'call', 'args']]) // Multiple calls
expect(fn.mock.calls[0][0]).toBe(2) // fn.mock.calls[0][0] — the first argument of the first call
Aliases
toBeCalled
→toHaveBeenCalled
toBeCalledWith
→toHaveBeenCalledWith
lastCalledWith
→toHaveBeenLastCalledWith
nthCalledWith
→toHaveBeenNthCalledWith
toReturnTimes
→toHaveReturnedTimes
toReturnWith
→toHaveReturnedWith
lastReturnedWith
→toHaveLastReturnedWith
nthReturnedWith
→toHaveNthReturnedWith
Misc
expect(new A()).toBeInstanceOf(A)
expect(() => {}).toEqual(expect.any(Function))
expect('pizza').toEqual(expect.anything())
Promise matchers
test('resolve to promise', () => {
expect.assertions(1)
// Make sure to add a return statement
return expect(Promise.resolve('promise')).resolves.toBe('promise')
return expect(Promise.reject('false promise')).rejects.toBeDefined()
return expect(Promise.reject(Error('fake promise'))).rejects.toThrow()
})
Or with async/await:
test('resolve to promise', async () => {
expect.assertions(2)
await expect(Promise.resolve('promise')).resolves.toBe('promise')
await expect(Promise.resolve('promise')).resolves.not.toBe('promise')
})
Thank you for reading this. In case you have any queries feel free to contact me by commenting below, see you soon in my next post