Back to Blogtesting

How to test react hook using jest

Learn how to effectively test React hooks using Jest and React Testing Library (RTL). This comprehensive guide covers setting up your environment, writing tests

testing
How to test react hook using jest

Testing React Hooks with Jest: A Comprehensive Guide

Suppose we have a react hook like this

import { useState } from 'react';

export function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);

  const increment = () => setCount((prevCount) => prevCount + 1);
  const decrement = () => setCount((prevCount) => prevCount - 1);
  const reset = () => setCount(initialValue);

  return { count, increment, decrement, reset };
}

I hope you have Jest & RTL already setup if not you can install it like this

npm install --save-dev jest @testing-library/react

To test this hook, we will use @testing-library/react's renderHook method along with Jest's describe and it syntax.

import { renderHook, act } from '@testing-library/react';
import { useCounter } from './useCounter';

describe('useCounter', () => {
  it('should initialize with the default value', () => {
    const { result } = renderHook(() => useCounter());

    expect(result.current.count).toBe(0);
  });

  it('should initialize with a custom value', () => {
    const { result } = renderHook(() => useCounter(10));

    expect(result.current.count).toBe(10);
  });

  it('should increment the count', () => {
    const { result } = renderHook(() => useCounter());

    act(() => {
      result.current.increment();
    });

    expect(result.current.count).toBe(1);
  });

  it('should decrement the count', () => {
    const { result } = renderHook(() => useCounter(1));

    act(() => {
      result.current.decrement();
    });

    expect(result.current.count).toBe(0);
  });

  it('should reset the count to initial value', () => {
    const { result } = renderHook(() => useCounter(10));

    act(() => {
      result.current.increment();
      result.current.reset();
    });

    expect(result.current.count).toBe(10);
  });
});

Explanation of the Test Structure

  1. describe: This block groups related tests together. It's helpful for organizing tests, especially when you have multiple hooks or functions to test.

  2. it: Each it block represents an individual test case. The string description should clearly explain what behavior the test is checking.

  3. renderHook: This function from React Testing Library is used to render your custom hook in a test environment. It returns an object containing the result, which represents the current state and methods returned by the hook.

  4. act: The act function ensures that all updates to the hook's state are applied before you make assertions. It’s essential when interacting with state-changing functions like increment, decrement, and reset.