Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using enzyme.mount().setProps with a react-redux Provider

I have a test which is setting props, to observe some changes in the component. The only complication is that I'm wrapping the rendered element in a <Provider> because there are some connected components further down the tree.

I'm rendering via

const el = () => <MyComponent prop1={ prop1 } />;
const wrapper = mount(<Provider store={store}>{ el() }</Provider>);

I'm then trying to observe some changes by using the following:

wrapper.setProps({ /* new props */ });
// expect()s etc.

The problem is that setProps() is not setting the props properly on the wrapped component. I assume that this is because <Provider> is not actually passing props through as it's not an HoC. Is there a better way to test this than just changing the locally scoped prop variables and re-rendering?

like image 589
GTF Avatar asked Feb 28 '17 12:02

GTF


2 Answers

Here's an approach using the setProps

import { Provider } from 'react-redux';


const renderComponent = properties => mount(
  React.createElement(
    props => (
      <Provider store={store}>
        <IntlProvider locale="en" defaultLocale="en" messages={messages}>
      <Router>
        <MyComponent {...props} />
      </Router>

      </Provider>
    ),
    properties))

Then in your test

it('should set some props', () => {
   const renderedComponent = renderComponent(props);
   renderedComponent.setProps({ /* some props */ } });

  expect(true).toBe(true);
})
like image 57
soupette Avatar answered Oct 14 '22 21:10

soupette


Another approach will be to use wrappingComponent.

For example, let say this is your provider

const ExampleProvider = ({ children }) => (
      <Provider store={store}>
        {children}
      </Provider>
    );

and then initialize wrapper as follows

wrapper = mount(<Component />, { wrappingComponent: ExampleProvider});

And then in test cases, you should be able to call wrapper.setProps directly.

like image 2
Vikas Kumar Avatar answered Oct 14 '22 23:10

Vikas Kumar