Can we skip a react hook ("getderivedstatefromprops") while unit test of a component using Enzyme and jest.
I am writing a Counter component, whose initial state is set as zero and new state is received from parent component, while simulate the increment or decrement function in unit test, changed state is override by parents initial state due to "getderivedstatefromprops" hook. In component it is called only once but in unit test when we update the component instance after simulating increment function it receive the initial value and state is changed to initial state. Is this any way while creating instance of component skip this hook?
export default class Counter extends React.Component<CounterProps,
CounterState> {
state = {
value: 0,
}
static getDerivedStateFromProps(props, state) {
return { ...state, value: props.initialValue }
}
incrementCounter = () => {
const { value } = this.state
const { id, maxValue, countChangeHandler, isDisabled } = this.props
const newValue = value + 1
if (newValue <= maxValue) {
countChangeHandler(id, newValue)
}
this.setState({ value: newValue })
}
render() {
const { value } = this.state
const { maxValue, isDisabled } = this.props
return (
<StyledCounter>
<Count disabled={isDisabled}>{value}</Count>
<Action onClick={this.incrementCounter}>
<Icon shape="plusGray" size="20px" />
</Action>
<Label>{'max ' + maxValue}</Label>
</StyledCounter>
)}
}
unit test:
describe('Counter components', () => {
function renderCounter(customProperties = {}) {
const properties = {
id: 124355,
initialValue: 3,
maxValue: 5,
isDisabled: false,
countChangeHandler: jest.fn(),
...customProperties,
}
const { output } = renderComponent(<Counter {...properties} />)
return output
}
afterEach(() => {
jest.resetAllMocks()
})
it('On multiple click on Increment button, counter value should not exceed max value.', () => {
const component = renderCounter()
component.find('div#increment').simulate('click')
component.find('div#increment').simulate('click')
component.find('div#increment').simulate('click')
component.find('Counter').update()
expect(component.find(Counter).state('value')).toEqual(5)
})
})
renderComponent is using Mount. unit test fails expecting 5, but received 3.
gDSFP
as well as it's going in your test. – skyboyer