How can I spyOn `useMutation` so that I can see what the values are being passed?

Viewed 5954

Rather than create a massive E2E test, I want to verify what the useMutation is receiving from the component. There is a lot of business logic before my component "posts" and I want to test that the GraphQL mutation function is receiving the shape of data.

Manually mocking the query doesn't provide value in this case, as it skips the business logic I want to keep track of. There is no value right now to let the query return full data & response, as my component will unmount and URL will change after successful data is returned.

So ideally, we just stop the test when the useMutation hook is called.

I am hoping to do something like:

const mutationSpy = jest.spyOn(graphQL, 'useMutation');
...
expect(mutationSpy).toHaveBeenCalledWith(myDataShape);
1 Answers

The best way to track whether a mutation has been called is to use the MockedProvider from @apollo/react-testing (react-native) or @apollo/client (react) to supply a callback function to your mock response that changes a variable in the test scope so that it may be checked once the test has been run. Something like this.

Here is the documentation:

https://www.apollographql.com/docs/react/development-testing/testing/#testing-mutation-components

test.js

let createMutationCalled = false

const mocks = [
    {
        request,
        result: () => {
            createMutationCalled = true
            return { data }
        }
    }
];

describe('test', () => {
    test('should call createTicket mutation', async () => {
        const { getByTestId } = render(
            <MockedProvider mocks={mocks}>
              <SelfReportPage />
            </MockedProvider>
        )

        let input = getByTestId('sr-description')
        let submit = getByTestId('sr-submit')
        fireEvent.changeText(input, 'Test text.')
        fireEvent.press(submit)

        await new Promise(r => setTimeout(r, 0));
    
        expect(createMutationCalled).toBe(true)
    })
})
Related