Skip to content

Commit e5c3465

Browse files
committed
Add stale closure test for useMutation
Reproduces apollographql#9111.
1 parent 2b0c412 commit e5c3465

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/react/hooks/__tests__/useMutation.test.tsx

+60
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,66 @@ describe('useMutation Hook', () => {
567567
expect(onError).toHaveBeenCalledTimes(1);
568568
expect(onError).toHaveBeenCalledWith(errors[0]);
569569
});
570+
571+
it('should never allow onCompleted handler to be stale', async () => {
572+
const CREATE_TODO_DATA = {
573+
createTodo: {
574+
id: 1,
575+
priority: 'Low',
576+
description: 'Get milk!',
577+
__typename: 'Todo',
578+
},
579+
};
580+
581+
const mocks = [
582+
{
583+
request: {
584+
query: CREATE_TODO_MUTATION,
585+
variables: {
586+
priority: 'Low',
587+
description: 'Get milk.',
588+
}
589+
},
590+
result: {
591+
data: CREATE_TODO_DATA,
592+
},
593+
}
594+
];
595+
596+
const onCompleted = jest.fn();
597+
const { result, rerender } = renderHook(
598+
({ onCompleted }) => {
599+
return useMutation<
600+
{ createTodo: Todo },
601+
{ priority: string, description: string }
602+
>(CREATE_TODO_MUTATION, { onCompleted });
603+
},
604+
{
605+
wrapper: ({ children }) => (
606+
<MockedProvider mocks={mocks}>
607+
{children}
608+
</MockedProvider>
609+
),
610+
initialProps: { onCompleted },
611+
},
612+
);
613+
614+
const onCompleted1 = jest.fn();
615+
rerender({ onCompleted: onCompleted1 });
616+
const createTodo = result.current[0];
617+
let fetchResult: any;
618+
await act(async () => {
619+
fetchResult = await createTodo({
620+
variables: { priority: 'Low', description: 'Get milk.' },
621+
});
622+
});
623+
624+
expect(fetchResult).toEqual({ data: CREATE_TODO_DATA });
625+
expect(result.current[1].data).toEqual(CREATE_TODO_DATA);
626+
expect(onCompleted).toHaveBeenCalledTimes(0);
627+
expect(onCompleted1).toHaveBeenCalledTimes(1);
628+
expect(onCompleted1).toHaveBeenCalledWith(CREATE_TODO_DATA);
629+
});
570630
});
571631

572632
describe('ROOT_MUTATION cache data', () => {

0 commit comments

Comments
 (0)