单元测试:用酶反应上下文api返回一个空对象 [英] Unit testing: react context api with enzyme return an empty object
问题描述
我第一次尝试使用React上下文API将信息从主要组件传递到他的孙子组件。
所以首先我创建了一个上下文
此处是定义上下文
父组件不在乎上下文,而在这里创建大子组件
到目前为止没有问题。一切正常。 ChildComponent已检索到上下文值。我无法设置上下文
最后一次期望失败,并且上下文值为空对象。所以foo是不确定的
我在这里重新创建了问题:
https://codesandbox.io/embed/x25yop4x5w?fontsize=14
感谢您的帮助
酶上下文
影响传统的React上下文,而不影响现代的上下文API。应该用以下命令来模拟它:
mount(< MyContext.Provider value = {{foo:987}}>< ChildComponent />< /MyContext.Provider>)
并用:
$断言b$ b
期望(wrapper.find('h2')。text())。toBe('上下文值:987');
I am trying for the first time to use React context API to pass information from a main component to his grandchild component.
So first I have created a context
Here is the main component that define the context
The parent component don't care about the context and is just here to create the grand child component
And here is the child component that reads the context
So far no problem. Everything works as expected. The ChildComponent have retrieve the context value.
The problem comes when I try to test it with jest/enzyme. I can't manage to set the context
The last expect fails and the context value is an empty object. So foo is undefined
I have recreated the problem here: https://codesandbox.io/embed/x25yop4x5w?fontsize=14
Thank you for your help
Enzyme context
affects legacy React context, not modern context API. It should be mocked with:
mount(<MyContext.Provider value={{foo: 987}}><ChildComponent/></MyContext.Provider>)
And asserted with:
expect(wrapper.find('h2').text()).toBe('Context value: 987');
这篇关于单元测试:用酶反应上下文api返回一个空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!