import { cleanup, render } from '@testing-library/react';
import { StrictMode, useEffect } from 'react';
import { afterEach, describe, expect, it } from 'vitest';
import { useIsMountedRef } from './hooks';
afterEach(cleanup);
describe('useIsMountedRef (#578)', () => {
it('reads true while mounted and false after unmount', () => {
let captured: { readonly current: boolean } | null = null;
function Probe() {
captured = useIsMountedRef();
return null;
}
const { unmount } = render();
// The guard every async callback reads: true for as long as the component is on screen...
expect(captured).not.toBeNull();
expect((captured as unknown as { current: boolean }).current).toBe(true);
unmount();
// ...and false afterwards, so a fetch resolving late can be dropped instead of calling setState
// on a component that no longer exists. Without the effect's cleanup this stays true, which is
// exactly the defect the hook exists to prevent.
expect((captured as unknown as { current: boolean }).current).toBe(false);
});
it('is re-armed by a StrictMode double-invoke (mount → cleanup → mount)', () => {
let captured: { readonly current: boolean } | null = null;
let effectRuns = 0;
function Probe() {
captured = useIsMountedRef();
useEffect(() => {
effectRuns += 1;
});
return null;
}
render(
);
// StrictMode in a dev build mounts, tears down, and remounts every effect. If that did not
// happen, this test would not be exercising re-arming at all, so assert it explicitly rather
// than assume it.
expect(effectRuns).toBeGreaterThan(1);
// The first cleanup set the flag false; the remount must set it back to true. Remove
// `ref.current = true` from the effect body and this reads false.
expect((captured as unknown as { current: boolean }).current).toBe(true);
});
});