Unit testing: react context api with enzyme return an empty object

若如初见. 提交于 2020-05-23 09:52:29

问题


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


回答1:


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');



回答2:


The method I've used to test components which require being mounted in within a context provider tree is to use the wrappingComponent and wrappingComponentProps options for mount.

This ensures that the return value of mount (the root component) is still the component you want to test (and will still support APIs/options that only work on the root component, such as setProps).

mount(<MyComponent />, {
  wrappingComponent: MyContext.Provider,
  wrappingComponentProps: {
    value: { foo: 987 },
  },
})


来源:https://stackoverflow.com/questions/55730219/unit-testing-react-context-api-with-enzyme-return-an-empty-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!