【发布时间】: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