enzyme: `.setProps()` doesn't trigger componentDidUpdate lifecycle method
When using shallow
, the .setProps()
method doesn’t trigger the componentDidUpdate lifecycle method. However, .setState()
does trigger it. It seems like they both should (or both shouldn’t).
simple example
describe('MyComponent', () => {
let spy;
before(function() {
spy = sinon.spy(MyComponent.prototype, 'componentDidUpdate');
});
after(function() {
spy.restore();
});
// fails
it('calls componentDidUpdate when setting props', () => {
const wrapper = shallow(<MyComponent color="yellow" />);
wrapper.setProps({ 'color': 'green' });
expect(spy.calledOnce).to.be.true;
});
// passes
it('calls componentDidUpdate when setting state', () => {
const wrapper = shallow(<MyComponent color="yellow" />);
wrapper.setState({ foo: 'bar' });
expect(spy.calledOnce).to.be.true;
});
});
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 12
- Comments: 30 (11 by maintainers)
@bricejlin #318 is hidden in the
lifecycleExperimental
flag. You can do with the flag for enabling all lifecycle methods inshallow
.At the moment I’m doing
The latest update seems to broke this again. node_modules/enzyme/build/ShallowWrapper.js line 552
The last condition make it that only state change will trigger instance.componentUpdate,
Sorry to bring an old thread back up, but I’m running into a similar issue detailed here, and I can’t seem to find any other solutions when searching. Here’s my test:
When I uncomment out
// mounted.instance().componentDidUpdate({});
, it works as expected, however I’m expecting thecomponentDidUpdate
method to be called with the props changing. I checked, the props are updating as they should so I was wondering if this is a known issue or if it’s something I’m doing wrong?In react-native
lifecycleExperimental
works forcomponentDidMount()
but not forcomponentDidUpdate()
.https://github.com/airbnb/enzyme/issues/1279
Solved it by using
Works as a charm, setprops are set, you just need to call a function again that triggers the component o re-render, it will trigger the componentDidUpdate function
@blainekasten thanks for that info. Funny - I didn’t even know
.setProps()
existed as a real API.The deprecation doesn’t affect us in this case, since
.setProps()
is achieved usingsetState()
of a parent wrapper component, anyway.FWIW,
setProps
is being deprecated.https://github.com/facebook/react/pull/5588/files http://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#new-deprecations-introduced-with-a-warning