Skip to content

Instantly share code, notes, and snippets.

@ovidiuch
Created May 25, 2017 07:56
Show Gist options
  • Save ovidiuch/ce6844b08db86217d0f4bae340209744 to your computer and use it in GitHub Desktop.
Save ovidiuch/ce6844b08db86217d0f4bae340209744 to your computer and use it in GitHub Desktop.
Enzyme mount() vs shallow() for component context providers
import React, { Component, PropTypes } from 'react';
import { shallow, mount } from 'enzyme';
class ContextProvider extends Component {
getChildContext() {
return {
foo: 'bar'
};
}
render() {
return this.props.children;
}
}
ContextProvider.childContextTypes = {
foo: PropTypes.string
};
class ContextReceiver extends Component {
render() {
return (
<div>
{this.context.foo}
</div>
);
}
}
ContextReceiver.contextTypes = {
foo: PropTypes.string
};
describe('context passing', () => {
it('mount', () => {
const wrapper = mount(
<ContextProvider>
<ContextReceiver />
</ContextProvider>
);
// Passes!
expect(wrapper.text()).toEqual('bar');
});
it('shallow', () => {
const wrapper = shallow(
<ContextProvider>
<ContextReceiver />
</ContextProvider>
);
// Fails: Expected "bar" Receiver "<ContextReceiver />"
// Which makes a lot of sense, because Shallow Rendering is meant to render
// only the top level component, which in this case is ContextProvider
expect(wrapper.text()).toEqual('bar');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment