我有一个想要测试的自定义 Hook 。它接收一个 redux 存储调度函数并返回一个函数。为了得到我想要做的结果:
const { result } = renderHook(() => { useSaveAuthenticationDataToStorages(useDispatch())});
但是,我收到错误:
Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a
发生这种情况是因为 useDispatch
并且没有连接存储。但是,我这里没有任何组件可以与提供程序一起包装。我只需要测试只是将数据保存到存储的钩子(Hook)。
如何修复它?
最佳答案
react hooks 测试库 docs对此进行更深入的探讨。然而,我们本质上缺少的是我们可以通过创建包装器来获得的提供者。首先我们声明一个组件作为我们的提供者:
import { Provider } from 'react-redux'
const ReduxProvider = ({ children, reduxStore }) => (
<Provider store={reduxStore}>{children}</Provider>
)
然后在我们的测试中我们调用
test("...", () => {
const store = configureStore();
const wrapper = ({ children }) => (
<ReduxProvider reduxStore={store}>{children}</ReduxProvider>
);
const { result } = renderHook(() => {
useSaveAuthenticationDataToStorages(useDispatch());
}, { wrapper });
// ... Rest of the logic
});
关于reactjs - 测试自定义 Hook : Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a <Provider>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59476912/