Enzyme: test componentWillReceiveProps failed

Created on 23 Mar 2017  路  6Comments  路  Source: enzymejs/enzyme

I'm going to test lifecycle functions including componentWillReceiveProps using enzyme.

Before anything else, my component should be wrapped materialUi styles and be connected with redux. Otherwise, there will be bugs in render function because I use material-ui components including FlatButton.

const wrapper = mount(
 <MuiThemeProvider muiTheme={muiTheme}>
      <Provider store={store}>
           <MemoryRouter>
              <MyComponent />
           </MemoryRouter>
      </Provider>
  </MuiThemeProvider>)

// absolutely fail
wrapper.find(MyComponent).setProps({ something })
expect(MyComponent.prototype.componentWillReceiveProps.calledOnce).toBe(true)

So the problem is that I can't use setProps() to MyComponent because enzyme doesn't allow applying non-root component. I'm not able to test componentWillReceiveProps or other necessary parts by changing props.

Is there any good way to set/change props of MyComponent?

Most helpful comment

wrapper.instance().componentWillReceiveProps() - iow, call it manually.

All 6 comments

wrapper.instance().componentWillReceiveProps() - iow, call it manually.

Sorry but I get this error.
TypeError: wrapper.instance(...).componentWillReceiveProps is not a function
Also I'm just wondering if it will call componentWillReceiveProps of MyComponent

Ah - you can only use it on the root.

What you want to do is shallow your MyComponent, and do all the individual tests there.

Yeah, shallow works well.
Finally how can I call reducer of MyComponent?

If you mean the reducer of a flux store, you'd shallow-render the wrapper, and assert on the child's props.

Thank you

Was this page helpful?
0 / 5 - 0 ratings