0

Hello I'm trying to test a state that is changed in the componentDidUpdate but is not enetering.

Code

componentDidUpdate (newProps) {
    const { dataSource } = newProps
    // set value for nextButtonDisabled in first results async load
    if (dataSource.length) {
        const newPaginationInfo = Object.assign({}, this.state.paginationInfo)
        newPaginationInfo.nextButtonDisabled = dataSource.length <= this.pageSize
        this.setState({ paginationInfo: newPaginationInfo }) /* eslint-disable-line react/no-did-update-set-state */
    }
}

State

this.state = {
    paginationInfo: {
        currentPage: 0,
        nextButtonDisabled: true
    }
}

And the test

it('should set nextButtonDisabled to false when gets new props.datasource if datasource length <= 20', () => {
    const component = shallow(<VehicleHistoryTable {...makeProps()} />)
    component.setProps({ dataSource: createDataSourceMock(3) })
    expect(component.instance().state.paginationInfo.nextButtonDisabled).toEqual(true)
})

The function createDataSourceMock() creates an array of numbers, in this case 3 rows.

Any suggestions?

P:S I'm trying to migrate to React 17

Jonathan
  • 469
  • 1
  • 6
  • 20
  • 1
    Not sure you're using the right args, this is the method signature `componentDidUpdate(prevProps, prevState, snapshot)` from https://reactjs.org/docs/react-component.html#componentdidupdate . So you can compare the previous props and state with the current ones. – sanjsanj Sep 23 '19 at 14:49
  • Isn't this an infinite loop? You set state in `componentDidUpdate`, triggering a re-render which calls `componentDidUpdate` again, no? See https://stackoverflow.com/questions/30528348/setstate-inside-of-componentdidupdate – ggorlen Sep 23 '19 at 14:51
  • Is there a [shouldComponentUpdate](https://reactjs.org/docs/react-component.html#shouldcomponentupdate) lifecycle method? Perhaps that is blocking the update? Also make sure you're using an enzyme version >= 3 as prior versions did not trigger the `componentDidUpdate` method on shallow render. – Jeff Wooden Sep 23 '19 at 14:55

0 Answers0