Skip to content

Unmount doesn't seem to be firing useEffect cleanup functions #847

Open
@kmarple1

Description

@kmarple1
  • 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions