Lee Goddard
Lee Goddard

Reputation: 11173

Test React-Redux with mock context and actions

How can I test a Reaect-Redux component and mock its context and actions?

With this, it can't find any actions:

    const wrapper = mount(
  <S437TransactionAuth
    store={store}
    s437updateGui="{mock.action.s437updateGUI}"
    setCurrentUserId="{mock.action.setCurrentUserId}"
  />,
        mockContext
    );

This can't find mock actions or context

    const wrapper = mount(
        <Provider store={store}>
            <S437TransactionAuth
                s437updateGui="{mock.action.s437updateGUI}"
                setCurrentUserId="{mock.action.setCurrentUserId}"
            />
        </Provider>,
        mockContext
    );

What is the standard practice? I'm using Mocha, for reasons beyond my control.

Upvotes: 1

Views: 876

Answers (2)

Michael Peyper
Michael Peyper

Reputation: 6944

Assuming you are using enzyme for doing the mounting, the context is supposed to be passed as

const wrapper = mount(
  <S437TransactionAuth
    // I'm assuming you have put your store in the context so I've removed store={store} for here
    s437updateGui="{mock.action.s437updateGUI}"
    setCurrentUserId="{mock.action.setCurrentUserId}"
  />,
        { context: mockContext }
    );

I've personally just used the react-redux Provider without doing anything with the second parameter of mount, like so

const wrapper = mount(
        <Provider store={store}>
            <S437TransactionAuth
                s437updateGui="{mock.action.s437updateGUI}"
                setCurrentUserId="{mock.action.setCurrentUserId}"
            />
        </Provider>
    );

Also, if you're not already using it, redux-mock-store makes testing connected components much easier but allowing you to set up an initial state to render, assert expected render in the component, or simulate user actions on the component with enzyme, and assert the expected actions against the mock store.

Upvotes: 1

CharlieBrown
CharlieBrown

Reputation: 4163

Our standard practice is to export both the connect component as default and the component itself as a named export.

connect is already tested for you so there's no point in verifying it's actually passing stuff from the Redux store to your component. What you can test is that your component uses that props correctly, which you can mock in your non-connected component.

You can also test your selectors and action creators you assign in mapStateToProps and mapDispatchToProps in isolation.

Last but not least, you can always simply configure your real store for the test (inside your describecalls!) and wrap your subject in a Provider with the real store. But this path could lead to you having to dispatch some actions to setup the state as your component expects it (like mocking an API call to have data, and so on).

Upvotes: 1

Related Questions