Describe the bug
When a component is shallow mounted the setProps function seems to be replacing(instead of merging) the props internally for the component when no change is made. Subsequent calls to setProps that _do_ yield a change causes the prevProps argument of componentDidUpdate to contain an incorrect value.
To Reproduce
The following example code throws an error showing that the previous props passed to componentDidUpdate is incorrect.
I was only able to reproduce this when using a custom shouldComponentUpdate implementation that uses isEqual to check the props
import React from 'react'
import { shallow } from 'enzyme'
import isEqual from 'lodash/isEqual'
class TestComponent extends React.Component {
static defaultProps = {
myProp: 'should exist',
}
shouldComponentUpdate(nextProps) {
return !isEqual(nextProps, this.props)
}
componentDidUpdate(prevProps) {
if (typeof prevProps.myProp === 'undefined') {
throw new Error('"myProp" disappeared')
}
}
render() {
return null
}
}
describe('Example', function() {
it('should pass', function() {
const fetchNamedRelationship = sinon.spy()
const wrapper = shallow(<TestComponent example="example" />)
// Nothing is changed here
wrapper.setProps({ example: 'example' })
// Add something new
wrapper.setProps({ somethingElse: '' })
})
})
Expected behavior
In the example above I expected prevProps to equal
{
myProp: 'should exist'
example: 'example'
}
instead it equals
{
example: 'example'
}
Additional context
My workaround is to use mount instead of shallow
Hi @omarjackman I think it's related to https://github.com/airbnb/enzyme/issues/1628
enzyme v3.3.0
react v16.2.0
mocha v3.2.0
@ljharb @omarjackman I thought it was connected to this issue https://github.com/airbnb/enzyme/issues/1628, but after checking my PR I realized that I was wrong. It is more similar to this one https://github.com/airbnb/enzyme/issues/1599.
Shallow wrapper sets props from .setProps() method if shouldComponentUpdate() is present and returns false.
is there a way to actually set fresh props without merging? I have a use case for that to avoid unnecessary mounting
Most helpful comment
Hi @omarjackman I think it's related to https://github.com/airbnb/enzyme/issues/1628