question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How do I write tests for higher order components in Enzyme.

See original GitHub issue

I have spent some time online searching for documents around how to do this. There seems to be a few ways. But I am not sure on which is the best way to do this.

This is what I have so far

My HOC

interface IStateProps {
    errorState: IErrorState;
    tList: IList;
}

interface IDispatchProps {
    fetch: () => any;
}

interface IState {
    isLoading: boolean;
}

interface IConnectedProps extends IStateProps, IDispatchProps {}

export class UnconnectedBrowserLoader extends React.Component<IConnectedProps, IState> {
    public state = {
        isLoading: true,
    };

    public render() {
        const {errorState} = this.props;
        if (errorState.error) {
            return (
                <div className="non-ideal">
                    <NonIdealState visual="error" title={"Could Not Load Tasks"}/>
                </div>
            );
        }
        if (this.state.isLoading) {
            return (
                <div className="non-ideal">
                    <NonIdealState visual={<Spinner/>}/>
                </div>
            );
        }
        return (
            <div className="body">
                <Container/>
            </div>
        );
    }

    public componentWillMount() {
        Promise.all([
            this.props.fetch(),
        ]).then(() => {
            this.setState({isLoading: false});
        });
    }
}

function mapStateToProps(state: IBrowserState): IStateProps {
    return {errorState: state.errorState, tList: state.taskList};
}

function mapDispatchToProps(dispatch: Dispatch<IBrowserState>): IDispatchProps {
    return bindActionCreators({
        fetch,
    }, dispatch);
}

export const BrowserLoader = connect(
    mapStateToProps, mapDispatchToProps,
)(UnconnectedBrowserLoader);

My tests now looks like this - WIP

describe("Browser tests", function() {
    test("test the browser loader for error case", () => {
        const mockStore = configureMockStore([thunk]);
        const store = mockStore({
            errorState: {
                error: "internal error"
            }
        });

        const wrapper = mount(<Provider store={store}><BrowserLoader/></Provider>);
        expect(wrapper.find('.non-ideal')).toHaveLength(1); // this works
        expect(wrapper.find('.body')).toHaveLength(0); // this works
    });
    test("test the browser loader", () => {
        const mockStore = configureMockStore([thunk]);
        const store = mockStore({});
        const dispatch = sinon.spy();
        const wrapper = shallow(
            <Provider store={store}><BrowserLoader/></Provider>
        );
       expect(wrapper.find('Connect(UnconnectedBrowserLoader)')).toHaveLength(1); //This works
       expect(wrapper.find('Connect(UnconnectedBrowserLoader)').props()).toEqual({}); // this works too

       // Not sure how to pass mapStateToProps and mapDispatchToProps.
        const uwrapper = shallow(<UnconnectedBrowserLoader dispatch={dispatch} store={store}/>); //This does not work it complains "Property store does not exist on IConnectedProps

        // I tried this too
       const uwrapper = wrapper.find('Connect(UnconnectedBrowserLoader)').shallow() // this does not work too - it gives error Could not find "store" in either the context or props of "Connect(UnconnectedBrowserLoader)". 
    });
});

What is it that I am doing wrong?! Can anyone point me to it? any help would be appreciated. SO link - http://stackoverflow.com/questions/44031658/enzyme-tests-for-higher-order-components-redux

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:7
  • Comments:25 (10 by maintainers)

github_iconTop GitHub Comments

16reactions
ljharbcommented, May 17, 2017

shallow-render the wrapper, do .dive(), and then write assertions on the enzyme wrapper that provides around the inner component.

9reactions
dabit1commented, Feb 1, 2018

I finally found a very good solution to get a wrapper from a decorated component. For shallowed components you can use dive() but there is no similar method for mounted components. This is the solution I did:

const wrapper = mount(shallow(<MyComponent />).get(0))

Works like a charm 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unit Testing Higher-Order Components with Enzyme and Jest
One of the common HOCs I write for every project of mine is called withConditional . Its purpose is to render a component...
Read more >
How to unit test a higher order component using jest and ...
How to unit test a higher order component using jest and enzyme in react ; Component · ComponentType } from ; import ·...
Read more >
How to test a React Higher Order Component using ... - Surevine
Recently I have had to test a React Higher Order Component using the fabulous react-testing-library but struggled to find how you can ...
Read more >
How to test High Order Components in React
Note: I'm assuming you are somewhat familiar to unit testing in JavaScript and know what a High Order Component is. I'm adding unit...
Read more >
Test Cases and Test Coverage for High Order Components
Higher Order Component : A function that takes a component and returns a new component. This is a composition approach to reuse component...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found