Skip to content

Commit 9938c0d

Browse files
committed
test: add regression case for function target closure
1 parent 7ae38d2 commit 9938c0d

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

tests/useResizeObserver.spec.tsx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { render, waitFor } from '@testing-library/react';
2+
import { useEvent } from '@rc-component/util';
3+
import React from 'react';
4+
import { useResizeObserver } from '../src';
5+
import { _el as elementListeners } from '../src/utils/observerUtil';
6+
7+
describe('useResizeObserver', () => {
8+
it('should observe latest element when target getter closes over stateful ref value', async () => {
9+
function Demo() {
10+
const [element, setElement] = React.useState<HTMLElement | null>(null);
11+
// `useEvent` keeps the getter identity stable while the closed-over DOM node
12+
// comes from state. If the hook only checks the function reference, it misses
13+
// the later state update from `null` to the actual element and never observes it.
14+
const getTarget = useEvent(() => element as HTMLElement);
15+
16+
useResizeObserver(true, getTarget);
17+
18+
return <div ref={setElement} data-testid="target" />;
19+
}
20+
21+
const { getByTestId } = render(<Demo />);
22+
const target = getByTestId('target');
23+
24+
await waitFor(() => {
25+
// Once the ref callback stores the DOM into state, the latest element should
26+
// still be observed even though the getter function itself never changes.
27+
expect(elementListeners.get(target)).toBeTruthy();
28+
});
29+
});
30+
});

0 commit comments

Comments
 (0)