JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
PrevNext

Learn the concept

Matchers and Assertions

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 matchersJavaScript
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');
  });
});

Real-World Applications

Use Cases

Validating the return value of a function that processes user input

Using `expect(result).toBe('expected_value')` for primitive values or `expect(object).toEqual({ ... })` for complex objects to ensure the function output matches the exact expected outcome.

Checking if an asynchronous API call returns a specific data structure

Employing `expect(response.data).toMatchObject({ id: expect.any(Number), name: expect.any(String) })` to verify that the API response contains the required fields with their correct types, without needing to match the entire object.

Ensuring an error handling mechanism correctly throws a specific type of error

Using `expect(() => dangerousFunction()).toThrow(MyCustomError)` or `expect(asyncCall()).rejects.toThrow('Error Message')` to confirm that error conditions are properly identified and handled.

Mini Projects

Matcher Practice for String Utility

beginner

Create a JavaScript utility file with functions for string manipulation (e.g., reverse, capitalize, check palindrome) and write Jest tests for each using various string matchers like `toMatch`, `toContain`, and `toHaveLength`.

Basic API Response Validation

intermediate

Simulate an API call that returns a JSON object. Write Jest tests using `toEqual`, `toMatchObject`, and `toHaveProperty` to validate the structure and content of the simulated API response.

Industry Examples

React Testing Library

React Testing Library, which often uses Jest as its test runner, leverages Jest matchers extensively for asserting DOM changes and component behavior. Matchers like `toBeInTheDocument()`, `toHaveTextContent()`, and `toBeDisabled()` (custom matchers from `@testing-library/jest-dom`) build upon Jest's core assertion capabilities to provide semantic UI tests.

Storybook (Interaction Tests)

Storybook's Interaction Tests feature often integrates with Jest, allowing developers to write tests that interact with UI components in a browser-like environment and then use Jest matchers to assert the state and behavior of the components after interactions.

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?
PrevNext