Testing the cache side effects of a mutation? react apollo client

Hello, I’m using apollo client.

Is it possible to test that the cache updates after a mutation? Specifically, there’s no refetchQuery or anything, but the mutation returns:
{
id,
items: [{ id, … }]
}

And I’m trying to expect on the place where the updated items would be, but it’s not rerendering. The result from the mutation is correct with the MockedProvider I’ve given it.

This works as expected while running the application like normal.

Is it possible to test this, and I’m doing something wrong or should I give up on doing this and instead expect on the result of the mutation with a custom tester component?

Hi @prscoelho :wave: thanks for posting! In general I recommend against unit testing implementation details such as the state of the cache. Your last sentence seems to be along the lines of what I’d recommend: asserting that the elements render as expected.

1 Like

Hey! Thanks for helping!

Yeah, testing that the rerender happens as expected was my original goal. However, the query lives in a different component, and the mutation changes that result. This happens in the cache through normalization. Which works correctly while running, but the rerender just don’t happen in jest (both components are being rendered in the test). What I wanted to test was that the rerender happens as expected, with the mutated state.

What I ended up implementing was a test component that renders the result of the mutation, and I think this is more around testing implementation details than the previous alternative that I couldn’t get to work.

Do I need special configuration in MockedProvider for the rerender to trigger?

@prscoelho sorry to hear there’s an issue in the testing environment. I’d be happy to take a closer look, do you have a public repo that demonstrates the problem?

Almost an entire year since and today I spent all day fighting MockedProvider so that I could get the data to update. Last time I worked around it, this time I needed it to work. Keep in mind, when running normally it works perfectly! (Not asking for help, just detailing the process in case anyone comes across this)

After mutation, the useQuery cached data did not merge with the data from the useMutation. I set addTypename=true, added the typename to the mocked data object I wanted to merge…

Eventually, I started getting another error: now it said I don’t have a mocked query, because adding the typename caused the query to somehow require a refetch. I think if you start running into this, you’re on the right path. It’s trying to merge but doesn’t have all fields so it’s refetching. Make sure you add __typename to the actual query, and make sure you return it in the mocked data. If your object has an array, and each item in the array is being normalized, make sure you add __typename to those mocked objects as well as in the graphql query.