Open In App

Testing Custom Hooks with React Testing Library

React hooks fall into two categories: built-in hooks provided by React itself and custom hooks, which are user-defined functions. The most commonly used built-in hooks are useState, useEffect, useMemo, and useCallback. Custom hooks in React are JavaScript functions that allow you to excerpt and reuse stateful logic from components.

They allow us to create reusable behaviour that can be used inside various components, thus minimizing code duplication. We can use other Hooks inside Custom hooks. Hook names start with use followed by a capital letter, like useState,useMemo (built-in), or useValidateImageUrl(custom).

In this article, we'll discuss the process of testing React Hooks. We'll create a custom hook and focus on creating test cases.

Pre-requisites:

Introduction and Testing

The react-hooks-testing-library provides functionalities for rendering custom hooks in test environment and asserting their result in different use cases.

Using this library, You do not have to worry about how to construct, render or interact with the react component in order to test your hook. You can just use the hook directly and test the results.

This library provides a testing experience as near as possible to natively using your hook from within a real component.

Here is an overview of the APIs provided by the library`@testing-library/react-hooks`:

   renderHook(callback: (props?: any) => any): RenderHookResult

Renders a custom hook inside a test. It will return an object containing properties and methods that you can use to interact with the rendered hook.

act(callback: () => void  |  Promise<any>): void

Wrap interactions with hooks inside act() to ensure proper execution of the callback and synchronisation with React's update cycle.

act() helps make your tests run similar to what real users experience when using your application.

Approach:

Examples:

Initialize a new React project :

npm create react-app custom-hooks-example
cd custom-hooks-example

Install @testing-library/react-hooks for testing our custom hook :

// if you're utilizing npm
npm install --save-dev @testing-library/react-hooks

// or if you're utilizing yarn
yarn add --dev @testing-library/react-hooks

Note: We will add @testing-library/react-hooks as DevDependency because a developer needs this package during development and testing.

List of devDependancies in package.json as shown below:

gfg-package-json-file-structure

gfg:package-json-file-structure

Folder structure:

Capture

gfg: React app Folder Structure

Example: To demonstrate testing custom hooks with react testing library.

// Filename : useCounter.js
import { useState } from 'react';

const useCounter = (startValue = 0, step = 1) => {
    const [count, setCount] = useState(startValue);

    const increment = () => {
        setCount(count + step);
    };

    const decrement = () => {
        setCount(count - step);
    };

    return { count, increment, decrement };
};

export default useCounter;
// Filename : Counter.js

import React from 'react';
import useCounter from './useCounter';

const Counter = () => {
    const { count, increment, decrement } = useCounter();

    return (
        <>
            <h2>Count: {count}</h2>
            <button onClick={increment}>Increment</button>
            <button onClick={decrement}>Decrement</button>
        </>
    );
};

export default Counter;
// Filename : useCounter.test.js

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

test('should use counter', () => {
    const { result } = renderHook(() => useCounter());

    expect(result.current.count).toBe(0);
    expect(typeof result.current.increment).toBe('function');
})

test('should increment count by 1', () => {
    const { result } = renderHook(() => useCounter());

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

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

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

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

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

test('should increment count by custom step', () => {
    const { result } = renderHook(() => useCounter(0, 2));

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

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

Run the tests to make sure everything is working correctly:

npm test

Output:

GFG - Testing Custom Hooks with React Testing Library

To test useCounter ,we will render it using the renderHook function provided by react-hooks-testing-library.

In the first test case, the result's current value matches the initial value what is returned by the hook.

In the second test case, After increment function is called, the current count value reflects the new value returned by the hook.

We have wrapped the increment call inside act().

Article Tags :