Enzyme: setProps overwrites props when component is shallow mounted

Created on 17 May 2018  路  4Comments  路  Source: enzymejs/enzyme

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

shallow bug help wanted

Most helpful comment

Hi @omarjackman I think it's related to https://github.com/airbnb/enzyme/issues/1628

All 4 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dschinkel picture dschinkel  路  3Comments

potapovDim picture potapovDim  路  3Comments

SandroMachado picture SandroMachado  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

aweary picture aweary  路  3Comments