Reputation: 41
I have an onCompleted that I am trying to test from my useMutation, I am using jest and react-testing-library. This is the piece of code I am trying to test
this is my react code:
const [deleteJobs] = useMutation<DeleteJobsMutation, MutationDeleteJobsArgs>(
mutationQuery,
{
refetchQueries: refetchQueries as string[],
onCompleted: () => (callback ? callback() : onCancel?.(null)),
},)
my mutation:
mutation deleteJobs($jobIds: [ID!]!) { deleteJobs(jobIds: $jobIds) {
successful}}
I have managed to mock it so it does call and I have also mocked it to succeed so I can test scenarios on success but I can't seem to work out how to get it to trigger the onCompleted
Upvotes: 3
Views: 7201
Reputation: 1399
Apollo Client's test suite has an example that demonstrates how to mock and test useMutation
's onCompleted
callback:
it('should allow passing an onCompleted handler to the execution function', async () => {
const CREATE_TODO_DATA = {
createTodo: {
id: 1,
priority: 'Low',
description: 'Get milk!',
__typename: 'Todo',
},
};
const mocks = [
{
request: {
query: CREATE_TODO_MUTATION,
variables: {
priority: 'Low',
description: 'Get milk.',
}
},
result: {
data: CREATE_TODO_DATA,
},
}
];
const { result } = renderHook(
() => useMutation<
{ createTodo: Todo },
{ priority: string, description: string }
>(CREATE_TODO_MUTATON),
{ wrapper: ({ children }) => (
<MockedProvider mocks={mocks}>
{children}
</MockedProvider>
)},
);
const createTodo = result.current[0];
let fetchResult: any;
const onCompleted = jest.fn();
const onError = jest.fn();
await act(async () => {
fetchResult = await createTodo({
variables: { priority: 'Low', description: 'Get milk.' },
onCompleted,
onError,
});
});
expect(fetchResult).toEqual({ data: CREATE_TODO_DATA });
expect(result.current[1].data).toEqual(CREATE_TODO_DATA);
expect(onCompleted).toHaveBeenCalledTimes(1);
expect(onCompleted).toHaveBeenCalledWith(CREATE_TODO_DATA);
expect(onError).toHaveBeenCalledTimes(0);
});
Upvotes: 1