Created
May 25, 2017 07:56
-
-
Save ovidiuch/ce6844b08db86217d0f4bae340209744 to your computer and use it in GitHub Desktop.
Enzyme mount() vs shallow() for component context providers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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