Context API HOC Unit testing

Viewed 791

I have a HOC component which wraps React's context API as follows

import React from 'react';
import { AppContext } from './Context';

export function withAppContext(Component) {
    return function WrapperComponent(props) {
        return (
            <AppContext.Consumer>
                {state => <Component {...props} context={state} />}
            </AppContext.Consumer>
        );
    };
}

and another component which uses this HOC as such

class Hello extends Component {
    render() {
        return (
            <Fragment>
                <p>{this.props.context.state.name}</p>
                <p>{this.props.context.state.age}</p>
                <p>{this.props.user}</p>
            </Fragment>
        )
    }
}

export default withAppContext(Hello);

I am planning to write a unit test that is going to test the Hello component. In order to achieve this , I have the following unit test

const getAppContext = (context = {
        state : {
            "name" : "Jane Doe",
            "age" : 28
        }
    }) => {

  // Will then mock the AppContext module being used in our Hello component
  jest.doMock('../../../context/Context', () => {
    return {
      AppContext: {
        Consumer: (props) => props.children(context)
      }
    }
  });

  // We will need to re-require after calling jest.doMock.
  // return the updated Hello module that now includes the mocked context
  return require('./Hello').Hello;
};

describe('Hello', () => {
    test('Verify state from Context API', ()=> {
        const Hello = getAppContext();
        const wrapper = mount(<Hello />);

    })

})

But it's failing at this line const wrapper = mount(<Hello />); with the following message

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your componentfrom the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `WrapperComponent`.

  46 |      test('Verify state from Context API', ()=> {
  47 |              const Hello = getAppContext();
> 48 |              const wrapper = mount(<Hello />);         |                              ^
  49 |              expect(wrapper.find('li').hostNodes().length).toBe(2);
  50 |              expect(wrapper.html()).toBe("<ul><li>Name : Jane Doe</li><li>Age : 28</li></ul>")
  51 |      })

Can you please let me know what I am doing wrong here?

Thanks

1 Answers

In ./Hello.js, the default export is the HOC.

The default export should be returned in getAppContext as "Hello" name is undefined in the required module.

return require('./Hello').default;
Related