test: add test for react memory leak warning in Popconfirm

This commit is contained in:
MadCcc 2021-12-29 11:31:50 +08:00
parent 19e4b578d9
commit 6d098783fc
3 changed files with 47 additions and 5 deletions

View File

@ -3,11 +3,12 @@ import * as React from 'react';
export default function useMountedRef() {
const mountedRef = React.useRef<boolean>(true);
React.useEffect(() => {
return () => {
React.useEffect(
() => () => {
mountedRef.current = false;
};
}, []);
},
[],
);
return mountedRef;
}

View File

@ -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 (
<Popconfirm
title="will unmount"
onConfirm={() =>
new Promise(resolve => {
setTimeout(() => {
setShow(false);
resolve();
}, 300);
})
}
>
<Button className="clickTarget">Test</Button>
</Popconfirm>
);
}
return <Button>Unmounted</Button>;
};
const wrapper = mount(
<div>
<Test />
</div>,
);
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();
});
});

View File

@ -58,7 +58,6 @@ const Popconfirm = React.forwardRef<unknown, PopconfirmProps>((props, ref) => {
if (mountedRef.current) {
setVisible(value);
}
props.onVisibleChange?.(value, e);
};