Dom-testing-library: Support fireEvent.change with valueAsNumber attribute

Created on 1 Oct 2019  路  3Comments  路  Source: testing-library/dom-testing-library

Describe the feature you'd like:

I was testing a range input which used an onChange prop that took the element's valueAsNumber attribute. The implementation was done this way to avoid having to transform the string into a number:

<input
  type="range"
  onChange={e => seekTo(e.target.valueAsNumber)}
  min={min}
  max={max}
  value={value}
  data-test="slider-input"
/>

So the tests were written taking that into account:

test('should trigger seek function when clicking the slider', () => {
  const { container } = render()
  const slider = container.querySelector('[data-test="slider-input"]')
  const value = 12345
  fireEvent.change(slider, {
    target: {
      valueAsNumber: value,
    },
  })
  expect(seekTo).toHaveBeenCalledWith(value)
})

The tests were failing with:

Expected mock function to have been called with:
    [12345]
But it was not called.

So after messing around a little bit, I tried firing the event with value instead of valueAsNumber and it worked.

fireEvent.change(slider, {
  target: {
    value,
  },
})

My implementation had to change to enable testing. My onChange function went from:

onChange={e => seekTo(e.target.valueAsNumber)}

to

onChange={e => seekTo(Number(e.target.value))}

...which is fine, but it would be nice to also support the valueAsNumber attribute.

Describe alternatives you've considered:

  • Documentation note warning about the lack of support
  • Console error warning about the lack of support when firing an event with this attribute


Most helpful comment

This was a source of frustration for me as well. I think you always have to specify the value though I'm not sure about the specifics. I guess we can close this issue?

All 3 comments

Have you tried providing value and valueAsNumber?

@eps1lon

Just tried, it worked! Thanks.

fireEvent.change(slider, {
  target: {
    value,
    valueAsNumber: value,
  },
})

This was a source of frustration for me as well. I think you always have to specify the value though I'm not sure about the specifics. I guess we can close this issue?

Was this page helpful?
0 / 5 - 0 ratings