From 6d098783fcd44a5b2eb7da509e38bbce59d9f108 Mon Sep 17 00:00:00 2001 From: MadCcc <1075746765@qq.com> Date: Wed, 29 Dec 2021 11:31:50 +0800 Subject: [PATCH] test: add test for react memory leak warning in Popconfirm --- components/_util/hooks/useMountedRef.ts | 9 ++-- components/popconfirm/__tests__/index.test.js | 42 +++++++++++++++++++ components/popconfirm/index.tsx | 1 - 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/components/_util/hooks/useMountedRef.ts b/components/_util/hooks/useMountedRef.ts index 40c80f29a2..134f358c74 100644 --- a/components/_util/hooks/useMountedRef.ts +++ b/components/_util/hooks/useMountedRef.ts @@ -3,11 +3,12 @@ import * as React from 'react'; export default function useMountedRef() { const mountedRef = React.useRef(true); - React.useEffect(() => { - return () => { + React.useEffect( + () => () => { mountedRef.current = false; - }; - }, []); + }, + [], + ); return mountedRef; } diff --git a/components/popconfirm/__tests__/index.test.js b/components/popconfirm/__tests__/index.test.js index f0698fb16d..f704e74310 100644 --- a/components/popconfirm/__tests__/index.test.js +++ b/components/popconfirm/__tests__/index.test.js @@ -5,6 +5,7 @@ import Popconfirm from '..'; import mountTest from '../../../tests/shared/mountTest'; import { sleep } from '../../../tests/utils'; import rtlTest from '../../../tests/shared/rtlTest'; +import Button from '../../button'; describe('Popconfirm', () => { mountTest(Popconfirm); @@ -223,4 +224,45 @@ describe('Popconfirm', () => { triggerNode.simulate('keydown', { key: 'Escape', keyCode: 27 }); expect(onVisibleChange).toHaveBeenLastCalledWith(false, eventObject); }); + + it('should not warn memory leaking if setState in async callback', async () => { + const error = jest.spyOn(console, 'error'); + + const Test = () => { + const [show, setShow] = React.useState(true); + + if (show) { + return ( + + new Promise(resolve => { + setTimeout(() => { + setShow(false); + resolve(); + }, 300); + }) + } + > + + + ); + } + return ; + }; + + const wrapper = mount( +
+ +
, + ); + + expect(wrapper.text()).toEqual('Test'); + const triggerNode = wrapper.find('.clickTarget').at(0); + triggerNode.simulate('click'); + wrapper.find('.ant-btn-primary').simulate('click'); + await sleep(500); + expect(wrapper.text()).toEqual('Unmounted'); + expect(error).not.toHaveBeenCalled(); + }); }); diff --git a/components/popconfirm/index.tsx b/components/popconfirm/index.tsx index 39467466b0..039e029ff6 100644 --- a/components/popconfirm/index.tsx +++ b/components/popconfirm/index.tsx @@ -58,7 +58,6 @@ const Popconfirm = React.forwardRef((props, ref) => { if (mountedRef.current) { setVisible(value); } - props.onVisibleChange?.(value, e); };