Tillitsdone
down Scroll to discover

Test Custom Hooks with React Testing Library

Learn how to effectively test React custom hooks using React Testing Library.

Discover best practices, common patterns, and avoid pitfalls when writing tests for your custom hooks.
thumbnail

How to Test Custom Hooks with React Testing Library

A minimalist modern concrete building facade with geometric patterns and sharp angles featuring rich brown and mahogany with cream colors captured from a low perspective angle with dramatic lighting high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Custom hooks are a powerful feature in React that allows us to extract component logic into reusable functions. But how do we ensure they work correctly? Let’s dive into testing custom hooks using React Testing Library.

Understanding the Basics

When testing custom hooks, we can’t test them directly since hooks can only be called inside React components. Instead, we need to create a test component that uses our hook. React Testing Library provides a special utility called renderHook that makes this process straightforward.

Let’s start with a simple example. Imagine we have a custom hook that manages a counter:

import { useState } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(prev => prev + 1);
const decrement = () => setCount(prev => prev - 1);
return { count, increment, decrement };
}

Abstract brush strokes texture with dynamic movement featuring lime and bright green tones against white background viewed from straight on angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Writing Your First Hook Test

Here’s how we can test our useCounter hook:

import { renderHook, act } from '@testing-library/react';
import { useCounter } from './useCounter';
describe('useCounter', () => {
test('should initialize with default value', () => {
const { result } = renderHook(() => useCounter());
expect(result.current.count).toBe(0);
});
test('should increment counter', () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
});

Best Practices and Common Patterns

  1. Always wrap state updates in act() The act utility ensures that all state updates are processed and applied before making assertions.

  2. Test initial states and props Make sure your hook initializes correctly with different props and default values.

  3. Test error cases Don’t forget to test how your hook handles errors and edge cases.

Dramatic sky scene with scattered clouds during golden hour featuring perfect red ochre and grapeseed colors shot from below looking up high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Testing Complex Scenarios

Sometimes hooks interact with APIs or have complex state management. Here’s how to handle those cases:

test('should handle async operations', async () => {
const { result } = renderHook(() => useDataFetching());
await act(async () => {
await result.current.fetchData();
});
expect(result.current.data).toBeDefined();
});

Common Pitfalls to Avoid

  1. Not cleaning up after tests
  2. Forgetting to wrap state updates in act()
  3. Testing implementation details instead of behavior
  4. Not testing error states

Remember, the goal is to test the behavior of your hook from the perspective of the components that will use it, not its internal implementation.

Abstract space art with nebula formations and cosmic clouds featuring umber walnut and iron colors with stark contrast captured from a wide angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.