enzyme: wrapper not updated after simulate('change').
Describe the bug During the test case, I perform a full mount on a component. After finding the input element, I simulate a change event in which I know the callback function is triggered since the value of the variable being passed back is asserted to be true. However, the props of the element do not get updated.
Test
import TripType from '.'
/** @test {TripType} */
describe('<TripType/>', () => {
/** @test {TripType#TripTypedisplays} */
it('should render the TripType class', () => {
const onChange = jest.fn()
const wrapper = shallow(<TripType name="test" onChange={onChange} />)
expect(wrapper).toMatchSnapshot()
})
/** @test {TripType#displays} */
it('should trigger the onChange event', () => {
const onChange = jest.fn()
const wrapper = mount(<TripType name="test" onChange={onChange} />)
wrapper.find('input[value="return"]').simulate('change', { target: { checked: true } })
expect(onChange).toBeCalled()
})
/** @test {TripType#displays} */
it('should change value', () => {
const wrapper = mount(<TripType name="test" defaultSelected="return" />)
expect(wrapper.find('input[value="return"]').prop('checked')).toBe(true)
expect(wrapper.find('input[value="oneway"]').prop('checked')).toBe(false)
wrapper.find('input[value="oneway"]').simulate('change', { target: { checked: true } })
expect(wrapper.find('input[value="return"]').prop('checked')).toBe(false)
expect(wrapper.find('input[value="oneway"]').prop('checked')).toBe(true)
})
})
In the above test third test fails. I tried wrapper.update()
, wrapper.forceUpdate()
but no luck.
Expected behavior Expected: false Received: false
But getting - Expected: false Received: true
Screenshots
Desktop (please complete the following information):
OS: MacOS High Sierra 10.13.6 React: “^16.0.0”,
About this issue
- Original URL
- State: open
- Created 5 years ago
- Comments: 18 (5 by maintainers)
@sharmapuneet This helped me with a similar problem:
.simulate('change', {target: {name: 'name_of_input', value: 'value'}})
(orchecked: true
in your case). The thing is if the event function sets state dynamically likestate.some_variable[event.target.name] = event.target.value;
, the name is unfortunately undefined without specifying it (even if set in HTML).Try
wrapper.find('input[value="oneway"]').prop('onChange', { target: { checked: true } })
instead of simulate.You may need a
wrapper.update()
; in general, I’d advise against ever usingsimulate
- it doesn’t actually simulate anything. Instead, explicitly invoke the prop function you want.@garncarz thank you so much! I hadn’t realized I needed to explicitly state the
name
attribute in the synthetic event; I was relying on my exiting JSX to handle that for me. This was so helpful!@garncarz Thank you so much!! That solved a lot of my pending unit tests.
This also works.
.prop('onChange')({ target: { checked: true } })
@garncarz thank you so much!!!