【问题标题】:React Testing Library merged with @testing-library/react-hooks, wrapper inconsistent in renderHookReact 测试库与 @testing-library/react-hooks 合并,renderHook 中的包装器不一致
【发布时间】:2022-11-10 20:28:22
【问题描述】:

@testing-library/react-hooks正如Advanced Hooks 文档中提到的那样,我曾经通过initialProps 传递模拟商店。假设我有一个代码:

import configureMockStore from 'redux-mock-store'
import { Provider } from 'react-redux'

const initialState = {}
const customStore = configureMockStore(initialState)

// this wrapper is nicely reusable across all tests
const wrapper = ({ children, store = customStore }) =>
  <Provider store={ store }>
    {children}
  </Provider>

const useCustomHook = () => {
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch({ type: 'ACTION' })
  }, [])
}

test('should get dispatched action', () => {
  renderHook(useCustomHook, {
    wrapper: wrapper,
    initialProps: {
      store: customStore
    }
  })

  expect(customStore.getActions()).toEqual([{ type: 'ACTION }])
})

如果我在更新(版本 10.4.5)和@testing-library/react-hooks 之前使用 RTL 运行此代码,一切都会按预期工作。但是在这些包合并后,renderHooks 函数中的wrapper 属性不接受除children 之外的任何其他属性。

第一次迭代引导我找到这个解决方案:

renderHook(useCustomHook, {
  wrapper: ({ children }) => (
   <Provider store={ customStore }>{children}</Provider>
  )
})

...这在可重用性方面不如我以前的包装器好。这个问题有什么好的解决办法吗?

【问题讨论】:

  • 你找到解决办法了吗?我有同样的问题,想要渲染钩子,但是钩子使用的状态是它没有被包装就没有被提供,会想要传递多个提供者所以想要一个助手,我可以用它覆盖商店中的状态。
  • @Jeremy 是的。我会回答rn

标签: react-testing-library react-hooks-testing-library


【解决方案1】:

解决方案:

const customWrapper = (store) => ({ children }) =>
  // this function is mentioned in question
  wrapper({
    children,
    store
  })
  
test('Some test #1', () => {
  const mockedState = {}
  const mockedStore = configureMockStore(mockedState)

  const { result } = renderHook(() => useCustomHook(), {
    wrapper: customWrapper(mockedStore)
  })
})

【讨论】:

    猜你喜欢
    • 2022-12-29
    • 2022-10-18
    • 2019-10-30
    • 2021-06-16
    • 2023-03-13
    • 2022-08-18
    • 2019-05-21
    • 2021-04-26
    • 2019-11-11
    相关资源
    最近更新 更多