Given this contrived example React component using apollo-client useMutation
hook with an update
method to customize the cache update, how can I write a unit test to test the update
method?
Because readQuery
will return null
if anything is query is not in the cache, I want a unit test to verify the read/writeQuery work as expected so we can prevent possible regressions.
Ideally I would like to test the customUpdateFunction
, but if that is not possible we can test the ExampleComponent
in a way to verify the cache update works as expected. As long as the result is adding some safety to the custom cache update in the useMutation
update
method.
function ExampleComponent() {
const {data} = useMutation(REMOVE_ITEM_MUTATION, {
variables: VARIABLES,
update: customUpdateFunction,
});
return ...
}
function customUpdateFunction(cache, data) {
const cachedData = readQuery({
query: LIST_QUERY,
});
if (!cachedData) {
return;
}
// Some immutable update to remove an item from a list
const updatedData = immutableUpdate(cachedData, data)
writeQuery({
query: LIST_QUERY,
data: updatedData,
});
}
I don't understand what is readQuery
and writeQuery
in your code.
If instead of readQuery
and writeQuery
you can use cache.readQuery
and cache.writeQuery
, then you can use import { InMemoryCache } from '@apollo/client'
to create cache and test it like this:
describe("customUpdateFunction", () => {
it("should remove data from LIST_QUERY in the cache", async () => {
//easy way to recive an initialCacheState is cache.extract()
const initialCacheState = ....
const cache = new InMemoryCache().restore(initialCacheState);
const data = .... // mutation result
customUpdateFunction(cache, data)
const cachedData = cache.readQuery({
query: LIST_QUERY,
});
expect(cachedData.something).not.toContain(data.something);
//or map array
//expect(cachedData.something.map(i=>i.id)).not.toContain(data.something.id);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.