gpt4 book ai didi

reactjs - 在 React 和 Redux 中使用 Enzyme 进行嵌套组件测试

转载 作者:行者123 更新时间:2023-12-03 13:00:02 25 4
gpt4 key购买 nike

我有一个组件SampleComponent,它安装了另一个“连接的组件”(即容器)。当我尝试通过 mount 测试 SampleComponent 时(因为我需要 componentDidMount),我收到错误:

Invariant Violation: Could not find "store" in either the context or props of "Connect(ContainerComponent)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(ContainerComponent)".

测试这个的最佳方法是什么?

最佳答案

enzyme 的安装采用可选参数。您需要的两个是

options.context:(对象[可选]):要传递到组件中的上下文

options.childContextTypes:(对象[可选]):包装器所有子级的合并 contextTypes
您可以使用选项对象安装 SampleComponent,如下所示:

const store = { 
subscribe: () => {},
dispatch: () => {},
getState: () => ({ ... whatever state you need to pass in ... })
}
const options = {
context: { store },
childContextTypes: { store: React.PropTypes.object.isRequired }
}

const _wrapper = mount(<SampleComponent {...defaultProps} />, options)

现在您的 SampleComponent 会将您提供的上下文传递给连接的组件

关于reactjs - 在 React 和 Redux 中使用 Enzyme 进行嵌套组件测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37798741/

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