When trying to write tests for a react component that contains a mutation, I'd like to verify that the mutation is actually called (and with the right variables). Currently the documentation on this topic suggests mocking the mutation result and testing that the component produces some sort of inspectable change as a result of the mutation.
https://www.apollographql.com/docs/react/recipes/testing.html#Testing-mutation-components
However this poses two problems:
One possible solution would be to allow more flexibility in how mocked responses are specified. If for example it were possible to pass in a method to the mock instead of a static result, then this could be utilized for this purpose, and perhaps other purposes as well:
let mutationWasCalled = false;
const mocks = [
{
request: {
query: expectedMutation,
variables: expectedVariables,
},
result: () => {
mutationWasCalled = true;
return dataToReturnFromMutation;
}
}
]
const component = (
<MockedProvider mocks={mocks}>
<ComponentBeingTested>
</MockedProvider>
)
// simulate click on the component
expect(mutationWasCalled).to.eq(true);
Another option that provides a bit less flexibility but would still solve this issue is to have some way to allow querying whether or not a specific mocked request was called, and\or how many times it was called.
Thanks for reading! Looking forward to your response.
I've run into this same situation where a component updates optimistically. The UI will change whether or not the mutation was actually called.
Thanks for the suggestion @noaelad - great idea! This change has been implemented and merged, and will be coming in the next react-apollo release. I'm going to keep this issue open to make sure we remember to update the docs to show that this is now possible. Thanks again!
Nice @hwillson thanks for implementing this! Looking forward to the next release to start using it =]
Most helpful comment
Thanks for the suggestion @noaelad - great idea! This change has been implemented and merged, and will be coming in the next
react-apollorelease. I'm going to keep this issue open to make sure we remember to update the docs to show that this is now possible. Thanks again!