Jest Unit testing — Use of Matchers (Part1)

Sanjana Human In Tech
2 min readMar 7, 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.

Basic matchers

//strict equality
expect(10).toBe(10)
//strict equality (!==)
expect(10).not.toBe(5)
//Deep equality
expect([6, 9]).toEqual([6, 9])
expect({ a: 7, b: undefined}).toEqual({ a: 7})
//strict equality (version Jest 23+)
expect({ a: undefined, b: 9}).not.toStrictEqual({ b: 10})

Numbers

expect(9).toBeGreaterThan(5)
expect(5).toBeGreaterThanOrEqual(5)
expect(4).toBeLessThan(2)
expect(3).toBeLessThanOrEqual(3)
expect(0.3 + 0.2).toBeCloseTo(0.5, 5)
expect(NaN).toEqual(expect.any(Number))

Strings

expect('hello jest').toMatch('jest')
expect('string').toEqual(expect.any(String))
expect('toffee').toMatch(/ff/)
expect('pizza').not.toMatch('burger')
expect(['pizza', 'toffee']).toEqual([expect.stringContaining('zz'), expect.stringMatching(/ff/)])

Truthiness

// Matches anything that an if statement treats as true 
(not false, 0, '', null, undefined, NaN)
xeTruthy()
// Matches anything that an if statement treats as false
(false, 0, '', null, undefined, NaN)
expect('').toBeFalsy()
// Matches only null
expect(null).toBeNull()
// Matches only undefined
expect(undefined).toBeUndefined()
// The opposite of toBeUndefined
expect(7).toBeDefined()
// Matches true or false
expect(true).toEqual(expect.any(Boolean))

Arrays

expect([]).toEqual(expect.any(Array))
expect(['Apple', 'Banana', 'Orange']).toHaveLength(3)
expect(['Apple', 'Apple', 'Apple']).toContain('Apple')
expect([{ a: 10 }, { a: 20 }]).toContainEqual({ a: 10 })
expect(['Apple', 'Banana', 'Orange']).toEqual(expect.arrayContaining(['Apple', 'Orange']))

Objects

expect({ a: 1 }).toHaveProperty('a')
expect({ a: 1 }).toHaveProperty('a', 1)
expect({ a: { b: 1 } }).toHaveProperty('a.b')
expect({ a: 1, b: 2 }).toMatchObject({ a: 1 })
expect({ a: 1, b: 2 }).toMatchObject({
a: expect.any(Number),
b: expect.any(Number)
})
expect([{ a: 1 }, { b: 2 }]).toEqual([
expect.objectContaining({ a: expect.any(Number) }),
expect.anything()
])

so these are the basic matchers to be used while writing unit test cases. For more reference refer below link

Thank you, comment below for any queries, hit the clap button to support.

--

--

Sanjana Human In Tech
Sanjana Human In Tech

Written by Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.