react-hooks-testing-library: Unmount doesn't seem to be firing useEffect cleanup functions

  • react-hooks-testing-library version: 8.0.0
  • react version: ^17.0.2
  • react-dom version (if applicable): ^17.0.2
  • react-test-renderer version (if applicable): n/a
  • node version: v14.17.6
  • npm (or yarn) version: 6.14.15

Relevant code or config:

The component I’m testing:

import { useState, useEffect } from "react";

const useDebounce = (value, delay) => {
    const [debouncedValue, setDebouncedValue] = useState(value);

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);

        return () => {
            clearTimeout(handler);
        };
    }, [value]);

    return debouncedValue;
};

export default useDebounce;

The test itself:

import { renderHook } from "@testing-library/react-hooks";
import useDebounce from "../useDebounce";

jest.useFakeTimers();
jest.spyOn(global, "clearTimeout");

describe("useDebounce", () => {
    test(`it should clear the timeout when unmounting`, () => {
        const value = "test";
        const delay = 1000;
        const { unmount } = renderHook(() => useDebounce(value, delay));
        expect(clearTimeout).not.toHaveBeenCalled();
        unmount();
        expect(clearTimeout).toHaveBeenCalled(); // fails here
    });
});

What you did:

I’m attempting to test that the useEffect cleanup function in my hook fires correctly.

What happened:

While it works properly when running normally, I can’t get unmount() to fire it.

Reproduction:

The above example reproduces the problem.

Problem description:

Unmount doesn’t seem to be properly cleanup up useEffects.

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 15
  • Comments: 15 (5 by maintainers)

Most upvoted comments

try skiping one thread cycle before expecting:

it('should call addEventListener on mount', async () => {
    const { unmount } = render(<Video src={src} />);
    expect(addEventListener).toHaveBeenCalled();
    unmount();

    // wait for a moment
    await new Promise((resolve) => setTimeout(resolve, 1));

    expect(removeEventListener).toHaveBeenCalled();
});    

@bhushanlaware it looks like you are rendering with react-testing-library, not react-hooks-testing-library so I suggest raising an issue with them for your case.

As a general reminder to others coming into this issue, if you are importing renderHook from @testing-library/react and not @testing-library/react-hooks then you should also be raising an issue with react-testing-library instead of tacking on a +1 to this issue.

Also a general suspicion that fake timers, unhandled async or mocked useEffect implementations are the likely cause here rather than the testing libraries involved. We generally defer the actual rendering to react itself, so if effects are not being cleanup up, a lot more people would be complaining about it.

Hello, if this can be of any help, here is a reproduction code:

// src/useMount.ts

import { useEffect, useState } from 'react'

export function useMount() {
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
    return () => {
      setMounted(false)
    }
  }, [])

  return mounted
}
// tests/unit/useMount.test.ts

import { renderHook } from '@testing-library/react'
import { useMount } from '../../src/useMount'

describe('useMount', () => {
  it('should be mounted', () => {
    const { result } = renderHook(useMount)
    expect(result.current).toBe(true)
  })

  it('should not be mounted after unmount', () => {
    const { result, unmount } = renderHook(useMount)
    unmount()
    expect(result.current).toBe(false)
  })
})

Result: image

Dependencies:

    "@testing-library/dom": "^9.3.1",
    "@testing-library/react": "^14.0.0",
    "@types/jest": "^29.5.2",
    "@types/react": "^18.2.13",
    "jest": "^29.5.0",
    "jest-environment-jsdom": "^29.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "ts-jest": "^29.1.0",
    "typescript": "^5.1.3"

This code is hosted here: https://github.com/saramorillon/hooks/tree/reproduction-847