From 015df5c1a7a404dae020cc821c7bd90ff8eec595 Mon Sep 17 00:00:00 2001 From: Wonsuk Choi Date: Sun, 25 Oct 2026 13:47:44 +0900 Subject: [PATCH] test(react-query/useMutation): assert that the mutation settles in the cache after unmount while the component state stays unchanged --- .../src/__tests__/useMutation.test.tsx | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/packages/react-query/src/__tests__/useMutation.test.tsx b/packages/react-query/src/__tests__/useMutation.test.tsx index 8c9b2e02bec..c459350f005 100644 --- a/packages/react-query/src/__tests__/useMutation.test.tsx +++ b/packages/react-query/src/__tests__/useMutation.test.tsx @@ -1273,11 +1273,10 @@ describe('useMutation', () => { }) it('should not change state if unmounted', async () => { - const consoleErrorMock = vi - .spyOn(console, 'error') - .mockReturnValue(undefined) + const states: Array = [] function Mutates() { - const { mutate } = useMutation({ mutationFn: () => sleep(10) }) + const { mutate, status } = useMutation({ mutationFn: () => sleep(10) }) + states.push(status) return } function Page() { @@ -1292,9 +1291,19 @@ describe('useMutation', () => { const { getByText } = renderWithClient(queryClient, ) fireEvent.click(getByText('mutate')) + await vi.advanceTimersByTimeAsync(0) + expect(states).toStrictEqual(['idle', 'pending']) + fireEvent.click(getByText('unmount')) - await vi.advanceTimersByTimeAsync(10) - expect(consoleErrorMock).not.toHaveBeenCalled() + expect(queryClient.getMutationCache().getAll()[0]?.state.status).toBe( + 'pending', + ) + + await vi.advanceTimersByTimeAsync(11) + expect(queryClient.getMutationCache().getAll()[0]?.state.status).toBe( + 'success', + ) + expect(states).toStrictEqual(['idle', 'pending']) }) it('should be able to throw an error when throwOnError is set to true', async () => {