enzymejs/enzyme

ReactWrapper::context() can only be called on the root

Open

#1631 opened on Apr 26, 2018

View on GitHub
 (3 comments) (1 reaction) (0 assignees)JavaScript (19,979 stars) (2,016 forks)batch import
API: mountAPI: shallowfeature requesthelp wanted

Description

Why does enzyme allow calling context() only on the root element? How do I check that a child receives some context value?

I have test like this:

class Child extends React.Component {
    render() {
        return <div />;
    }
}

Child.contextTypes = {
    intl: intlShape,
};

const store = configureStore()({ locale: 'es' });
const wrapper = mount(
    <ConnectedIntlProvider>
        <Child id="child" />
    </ConnectedIntlProvider>,
    { context: { store } }
);
wrapper.find('#child').context();

...and I'm getting ReactWrapper::context() can only be called on the root.

Calling .props() on the found component does work. Why not .context()?

BTW here's a test that achieves what I wanted to make my intentions more clear. It doesn't use Enzyme, but rather ReactDOM.

it('uses locale from store', () => {
    class Child extends React.Component {
        render() {
            return <div />;
        }
    }

    Child.contextTypes = {
        intl: intlShape,
    };

    const store = configureStore()({ locale: 'es' });
    const div = document.createElement('div');
    let child;
    ReactDOM.render(
        <ConnectedIntlProvider store={store}>
            <Child
                ref={(c) => {
                    child = c;
                }}
            />
        </ConnectedIntlProvider>,
        div
    );
    const locale = child && child.context && child.context.intl && child.context.intl.locale;
    ReactDOM.unmountComponentAtNode(div);
    expect(locale).toEqual('es');
});

Isn't there an easier way to do the same with Enzyme?

Contributor guide