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

后端 未结 2 1135
粉色の甜心
粉色の甜心 2021-01-14 15:21

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

相关标签:
2条回答
  • 2021-01-14 15:57

    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 },
      },
    })
    
    0 讨论(0)
  • 2021-01-14 16:10

    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');
    
    0 讨论(0)
提交回复
热议问题