enzymejs/enzyme

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

Open

#1631 aperta il 26 apr 2018

Vedi su GitHub
 (3 commenti) (1 reazione) (0 assegnatari)JavaScript (2016 fork)batch import
API: mountAPI: shallowfeature requesthelp wanted

Metriche repository

Star
 (19.979 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

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?

Guida contributor