Friday, April 21, 2017

JavaScript: Some Tips for Using MobX's Provider with Enzyme, etc.

Recently, we decided to move from using React's context functionality directly, to using MobX's Provider feature. Updating the code was a little painful, but not nearly as hard as trying to move from React Router v2 to v4! There were a few things that were hard in particular, such as updating all of the Enzyme-based tests. If you need to do the same thing, here are some tips:

First of all, start by reading all the documentation on Provider and inject. I'm not going to duplicate that here.

Let's suppose you have a component named MyComponent, and you have a MobX store named myStore.

If you're using a function-based component like:

const MyComponent = inject('myStore')(observer(cssModules(
    ({ myStore }) => <div>hi!</div>,
export default MyComponent;

Then to set the propTypes, you'll need to write:

MyComponent.wrappedComponent.propsTypes = { myStore: PropTypes.object.isRequired };

Thankfully, you'll get a warning if you get this one wrong.

In this case, the class-based syntax with decorators looks a bit nicer:

export default class MyComponent extends Component {
    static propTypes = {
        myStore: PropTypes.object.isRequired,
    render() {
        return <div>hi!</div>;

If you're using shallow to test MyComponent, then you should use .wrappedComponent, and pass myStore as a prop directly (which is one of my favorite features of how Provider works):

wrapper = shallow(<MyComponent.wrappedComponent myStore={ myStore } />);

If you're using mount, don't use wrappedComponent. Instead use Provider:

wrapper = mount(
    <Provider myStore={ myStore }>
        <MyComponent />

If you're using mount, and you see some code like:


You'll probably need to change it to:


If you are in a weird situation where you have to use context and Provider, you're going to find out that Enzyme won't pass any context to Provider since Provider isn't expecting it. Hence, nested components won't get the context that they need. To work around that problem (which is really a problem with how Enzyme works), you can do something like:

    wrapper = mount(
        <Provider myStore={ myStore }>
                <MyOtherComponentThatNeedsContext />
            context: { mySpecialContextData },
            childContextTypes: {
                mySpecialContextData: PropTypes.object.isRequired

Anyway, that's all I have for now. I'll keep updating this blog post with more tips as I find them.

No comments: