From 90b5aebdebce17cb12d9ad1b25e0dd270a056c9b Mon Sep 17 00:00:00 2001 From: Brian Kim Date: Tue, 22 Jun 2021 17:07:14 -0400 Subject: [PATCH] add test for unmounting in StrictMode --- src/react/hooks/__tests__/useQuery.test.tsx | 54 +++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/react/hooks/__tests__/useQuery.test.tsx b/src/react/hooks/__tests__/useQuery.test.tsx index 6907c836e21..76feb391398 100644 --- a/src/react/hooks/__tests__/useQuery.test.tsx +++ b/src/react/hooks/__tests__/useQuery.test.tsx @@ -677,6 +677,60 @@ describe('useQuery Hook', () => { }).then(resolve, reject); }); + itAsync('should stop polling when the component is unmounted when using StrictMode', async (resolve, reject) => { + const mocks = [ + ...CAR_MOCKS, + ...CAR_MOCKS, + ...CAR_MOCKS, + ...CAR_MOCKS, + ]; + + const mockLink = new MockLink(mocks).setOnError(reject); + + const linkRequestSpy = jest.spyOn(mockLink, 'request'); + + let renderCount = 0; + const QueryComponent = ({ unmount }: { unmount: () => void }) => { + const { data, loading } = useQuery(CAR_QUERY, { pollInterval: 10 }); + switch (++renderCount) { + case 1: + case 2: + expect(loading).toBeTruthy(); + break; + case 3: + case 4: + expect(loading).toBeFalsy(); + expect(data).toEqual(CAR_RESULT_DATA); + expect(linkRequestSpy).toHaveBeenCalledTimes(1); + if (renderCount === 3) { + unmount(); + } + break; + default: + reject("unreached"); + } + return null; + }; + + const Component = () => { + const [queryMounted, setQueryMounted] = useState(true); + const unmount = () => setTimeout(() => setQueryMounted(false), 0); + return <>{queryMounted && }; + }; + + render( + + + + + + ); + + return wait(() => { + expect(linkRequestSpy).toHaveBeenCalledTimes(1); + }).then(resolve, reject); + }); + itAsync( 'should not throw an error if `stopPolling` is called manually after ' + 'a component has unmounted (even though polling has already been ' +