JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
PrevNext
testing
junior
jest

What are the most commonly used Jest matchers?

jest
matchers
assertions
expect
Quick Answer

Jest matchers are methods used with expect() to test values. Common ones include toBe() for exact equality, toEqual() for deep equality, toBeTruthy()/toBeFalsy() for boolean checks, toContain() for arrays/strings, and toThrow() for errors.

Detailed Explanation

Equality Matchers:

  • toBe(): Exact equality (===, same reference)
  • toEqual(): Deep equality (for objects/arrays)
  • toStrictEqual(): Strict deep equality (checks undefined)

Truthiness:

  • toBeTruthy() / toBeFalsy()
  • toBeNull() / toBeUndefined() / toBeDefined()

Numbers:

  • toBeGreaterThan() / toBeLessThan()
  • toBeCloseTo(): For floating point

Strings:

  • toMatch(): Regex matching
  • toContain(): Substring check

Arrays/Iterables:

  • toContain(): Item in array
  • toHaveLength(): Array/string length

Objects:

  • toHaveProperty(): Check property exists
  • toMatchObject(): Partial object matching

Code Examples

Common matchers
describe('Jest matchers', () => {
  // Equality
  test('toBe vs toEqual', () => {
    expect(2 + 2).toBe(4);              // Exact equality
    expect({ a: 1 }).toEqual({ a: 1 }); // Deep equality
    expect({ a: 1 }).not.toBe({ a: 1 }); // Different references!
  });

  // Truthiness
  test('truthiness', () => {
    expect(true).toBeTruthy();
    expect(0).toBeFalsy();
    expect(null).toBeNull();
    expect(undefined).toBeUndefined();
    expect('value').toBeDefined();
  });

  // Numbers
  test('numbers', () => {
    expect(10).toBeGreaterThan(5);
    expect(5).toBeLessThanOrEqual(5);
    expect(0.1 + 0.2).toBeCloseTo(0.3); // Floating point!
  });

  // Strings
  test('strings', () => {
    expect('hello world').toMatch(/world/);
    expect('hello world').toContain('world');
  });

  // Arrays
  test('arrays', () => {
    expect([1, 2, 3]).toContain(2);
    expect([1, 2, 3]).toHaveLength(3);
    expect(['apple', 'banana']).toContainEqual('banana');
  });
});

Resources

Jest Expect API

docs

Related Questions

What is unit testing and why is it important?

junior
basics

How do you test asynchronous code in Jest?

junior
async
Previous
What is unit testing and why is it important?
Next
How do you use beforeEach, afterEach, beforeAll, and afterAll in Jest?