gpt4 book ai didi

react-testing-library - React Testing Library 与@testing-library/react-hooks 合并,renderHook 中的 wrapper 不一致

转载 作者:行者123 更新时间:2023-12-05 03:24:10 25 4
gpt4 key购买 nike

使用@testing-library/react-hooks 我过去常常通过initialProps 传递模拟存储,正如Advanced Hooks 中提到的那样文档。假设我有一个代码:

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>
)
})

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

最佳答案

解决方法:

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)
})
})

关于react-testing-library - React Testing Library 与@testing-library/react-hooks 合并,renderHook 中的 wrapper 不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72346908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com