Skip to content

Commit a0022cf

Browse files
author
Kent C. Dodds
committed
docs: add FAQ for the change event
1 parent 32f3e65 commit a0022cf

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,61 @@ Feel free to contribute more!
706706
707707
<details>
708708
709+
<summary>How do I test input onChange handlers?</summary>
710+
711+
TL;DR:
712+
[Go to the `on-change.js` example](https://codesandbox.io/s/github/kentcdodds/react-testing-library-examples/tree/master/?module=%2Fsrc%2F__tests__%2Fon-change.js&previewwindow=tests)
713+
714+
In summary:
715+
716+
```javascript
717+
import React from 'react'
718+
import 'react-testing-library/cleanup-after-each'
719+
import {render, fireEvent} from 'react-testing-library'
720+
721+
test('change values via the fireEvent.change method', () => {
722+
const handleChange = jest.fn()
723+
const {container} = render(<input type="text" onChange={handleChange} />)
724+
const input = container.firstChild
725+
fireEvent.change(input, {target: {value: 'a'}})
726+
expect(handleChange).toHaveBeenCalledTimes(1)
727+
expect(input.value).toBe('a')
728+
})
729+
730+
test('checkboxes (and radios) must use fireEvent.click', () => {
731+
const handleChange = jest.fn()
732+
const {container} = render(<input type="checkbox" onChange={handleChange} />)
733+
const checkbox = container.firstChild
734+
fireEvent.click(checkbox)
735+
expect(handleChange).toHaveBeenCalledTimes(1)
736+
expect(checkbox.checked).toBe(true)
737+
})
738+
```
739+
740+
If you've used enzyme or React's TestUtils, you may be accustomed to changing
741+
inputs like so:
742+
743+
```javascript
744+
input.value = 'a'
745+
Simulate.change(input)
746+
```
747+
748+
We can't do this with react-testing-library because React actually keeps track
749+
of any time you assign the `value` property on an `input` and so when you fire
750+
the `change` event, React thinks that the value hasn't actually been changed.
751+
752+
This works for Simulate because they use internal APIs to fire special simulated
753+
events. With react-testing-library, we try to avoid implementation details to
754+
make your tests more resiliant.
755+
756+
So we have it worked out for the change event handler to set the property for
757+
you in a way that's not trackable by React. This is why you must pass the value
758+
as part of the `change` method call.
759+
760+
</details>
761+
762+
<details>
763+
709764
<summary>Which get method should I use?</summary>
710765
711766
Based on [the Guiding Principles](#guiding-principles), your test should

0 commit comments

Comments
 (0)