[英]How to write unit test for ApolloClient cache update using readQuery/writeQuery?
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?鉴于这个人为的示例 React 组件使用 apollo-client
useMutation
挂钩和update
方法来自定义缓存更新,我如何编写单元测试来测试update
方法?
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.因为如果任何查询不在缓存中,
readQuery
将返回null
,所以我想要一个单元测试来验证读/写查询是否按预期工作,这样我们就可以防止可能的回归。
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.理想情况下,我想测试
customUpdateFunction
,但如果这不可能,我们可以以某种方式测试ExampleComponent
以验证缓存更新是否按预期工作。 As long as the result is adding some safety to the custom cache update in the useMutation
update
method.只要结果是在
useMutation
update
方法中为自定义缓存更新增加了一些安全性。
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.我不明白您的代码中的
readQuery
和writeQuery
是什么。
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:如果您可以使用
cache.readQuery
cache.writeQuery
readQuery
writeQuery
您可以使用import { InMemoryCache } from '@apollo/client'
创建缓存并像这样测试它:
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);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.