Skip to content

Commit fbee387

Browse files
committed
add test case
1 parent 7a573be commit fbee387

2 files changed

Lines changed: 39 additions & 10 deletions

File tree

src/index.tsx

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,21 @@ const MutateObserver: React.FC<MutationObserverProps> = props => {
1818

1919
const canRef = React.isValidElement(children) && supportRef(children);
2020

21+
const originRef: React.RefObject<HTMLElement> = canRef
22+
? (children as any)?.ref
23+
: null;
24+
2125
useEffect(() => {
2226
if (!canUseDom()) {
2327
return;
2428
}
29+
2530
let instance: MutationObserver;
26-
const currentElement = findDOMNode(wrapperRef.current!);
31+
32+
const currentElement = findDOMNode(
33+
originRef?.current || wrapperRef?.current,
34+
);
35+
2736
if (currentElement && 'MutationObserver' in window) {
2837
instance = new MutationObserver(onMutate);
2938
instance.observe(currentElement, options);
@@ -32,7 +41,7 @@ const MutateObserver: React.FC<MutationObserverProps> = props => {
3241
instance?.takeRecords();
3342
instance?.disconnect();
3443
};
35-
}, [options, onMutate]);
44+
}, [options, originRef, onMutate]);
3645

3746
if (!children) {
3847
if (process.env.NODE_ENV !== 'production') {

tests/index.test.tsx

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,32 @@ describe('MutateObserver', () => {
2929
});
3030
});
3131

32-
it('StrictMode', () => {
33-
const { container } = render(
34-
<MutateObserver>
35-
<div>test</div>
36-
</MutateObserver>,
37-
{ wrapper: React.StrictMode },
38-
);
39-
expect(container).toMatchSnapshot();
32+
it('findDOMNode should not error in React.StrictMode', () => {
33+
const fn = jest.fn();
34+
const buttonRef = React.createRef<HTMLButtonElement>();
35+
const warnSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
36+
const Demo = React.forwardRef<
37+
HTMLButtonElement,
38+
React.HTMLAttributes<HTMLButtonElement>
39+
>((props, ref) => {
40+
const [flag, setFlag] = React.useState<boolean>(true);
41+
return (
42+
<React.StrictMode>
43+
<MutateObserver onMutate={fn}>
44+
<button
45+
{...props}
46+
ref={ref}
47+
className={flag ? 'aaa' : 'bbb'}
48+
onClick={() => setFlag(!flag)}
49+
>
50+
click
51+
</button>
52+
</MutateObserver>
53+
</React.StrictMode>
54+
);
55+
});
56+
const { container } = render(<Demo ref={buttonRef} />);
57+
fireEvent.click(container.querySelector('button')!);
58+
expect(warnSpy).not.toHaveBeenCalled();
59+
warnSpy.mockRestore();
4060
});

0 commit comments

Comments
 (0)