CodexBloom - Programming Q&A Platform

Testing a Custom Hook in React with Jest and React Testing Library

šŸ‘€ Views: 48 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-21
react jest unit-testing JavaScript

I keep running into I've searched everywhere and can't find a clear answer... I'm trying to write unit tests for a custom React hook that manages a countdown timer. The hook works well in my application, but I'm struggling to test it effectively using Jest and React Testing Library. My hook looks like this: ```javascript import { useEffect, useState } from 'react'; const useCountdown = (initialCount, onComplete) => { const [count, setCount] = useState(initialCount); useEffect(() => { if (count <= 0) { onComplete(); return; } const timerId = setInterval(() => { setCount(prevCount => prevCount - 1); }, 1000); return () => clearInterval(timerId); }, [count, onComplete]); return count; }; export default useCountdown; ``` I've written a test for it that looks like this: ```javascript import { renderHook, act } from '@testing-library/react-hooks'; import useCountdown from './useCountdown'; describe('useCountdown', () => { it('counts down to zero', () => { const onComplete = jest.fn(); const { result } = renderHook(() => useCountdown(3, onComplete)); expect(result.current).toBe(3); act(() => jest.advanceTimersByTime(1000)); expect(result.current).toBe(2); act(() => jest.advanceTimersByTime(1000)); expect(result.current).toBe(1); act(() => jest.advanceTimersByTime(1000)); expect(onComplete).toHaveBeenCalled(); expect(result.current).toBe(0); }); }); ``` However, I'm working with an scenario where the test fails with the behavior message: `TypeError: setInterval is not a function`. I've tried using `jest.useFakeTimers()` at the beginning of my test, but that doesn't seem to resolve the scenario. I also checked that I’m not importing anything that conflicts with `setInterval`. Can anyone spot what I might be missing or any best practices for testing hooks like this? My versions are React 17 and @testing-library/react-hooks 7.0. This is part of a larger web app I'm building. I'm on Ubuntu 20.04 using the latest version of Javascript. Could this be a known issue? I'm working in a macOS environment.