【问题标题】:How to clear RTK Query cache in tests between requests when using MSW and Jest?使用 MSW 和 Jest 时如何在请求之间的测试中清除 RTK 查询缓存?
【发布时间】:2021-09-01 01:28:00
【问题描述】:

我正在使用 Redux Toolkit 和带有 MSW 的 RTK Query 进行模拟,但是当我尝试在测试中返回错误时,我似乎得到了相同的数据。我怀疑这是 RTK 查询缓存行为的问题,并尝试使用工具包 createApi 方法的这些选项禁用它,但它们似乎没有解决这个问题:

keepUnusedDataFor: 0,
refetchOnMountOrArgChange: true,
refetchOnFocus: true,
refetchOnReconnect: true,

在 MSW 文档中,它提供了使用其他库时如何解决此问题的示例:https://mswjs.io/docs/faq#why-do-i-get-stale-responses-when-using-react-queryswretc

// react-query example
import { QueryCache } from 'react-query'

const queryCache = new QueryCache()

afterEach(() => {
  queryCache.clear()
})

// swr example
import { cache } from 'swr'

beforeEach(() => {
  cache.clear()
})

在使用 Redux Toolkit 和 RTK Query 时,我怎样才能达到同样的效果?

【问题讨论】:

    标签: redux jestjs redux-toolkit msw rtk-query


    【解决方案1】:

    我可以建议阅读 RTK 查询测试:https://github.com/reduxjs/redux-toolkit/blob/18368afe9bd948dabbfdd9e99b9e334d9a7beedf/src/query/tests/helpers.tsx#L153-L166

    这就是我们所做的:

      const refObj = {
        api,
        store: initialStore,
        wrapper: withProvider(initialStore),
      }
      let cleanupListeners: () => void
    
      beforeEach(() => {
        const store = getStore() as StoreType
        refObj.store = store
        refObj.wrapper = withProvider(store)
        if (!withoutListeners) {
          cleanupListeners = setupListeners(store.dispatch)
        }
      })
      afterEach(() => {
        if (!withoutListeners) {
          cleanupListeners()
        }
        refObj.store.dispatch(api.util.resetApiState())
      })
    

    所以你正在寻找dispatch(api.util.resetApiState())

    【讨论】:

    • 如果您的问题得到解答,请接受答案 :) 特别是对于 RTK-Q,这是非常新的,接受的答案将有助于其他用户的发现:)
    【解决方案2】:

    基于上述答案,这就是我在我的应用中所做的:

    beforeEach(() => {
      const { result } = renderHook(() => useAppDispatch(), { wrapper });
      const dispatch = result.current;
    
      dispatch(myApi.util.resetApiState());
    });
    

    wrapper 这里是 Redux 和其他上下文的提供者。

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 1970-01-01
      • 2021-12-01
      • 2022-11-21
      • 2019-02-11
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多