The behavior of userEvent.click() is inconsistent with what happens in the browser under the specific condition when I preventDefault inside onPointerDown:
test("clicking doesn't work :(", async () => {
const user = userEvent.setup()
const spy = vi.fn(() => console.log('clicked!'))
render(
<Button
data-testid='clickme'
onClick={spy}
onPointerDown={(e) => {
e.preventDefault() // <-- the problem
}}
>
Click Me
</Button>
)
await user.click(screen.getByTestId('clickme'))
expect(spy).toHaveBeenCalledOnce() // ā fails
})
If I comment out the problematic line (e.preventDefault()), the test passes:
More importantly, if I put this exact same button on the page and click it (in Chrome 123.0.6312.124), it works fine; the onClick fires as expected.
<Button
onClick={() => console.log('clicked!')} // <-- ok
onPointerDown={(e) => {
e.preventDefault()
}}
>
Click Me
</Button>
So userEvent.click() is doing something differently than what seems be happening with the real user interaction.
Leaving aside the question of whether the code inside onPointerDown is a good idea or not (my real code is a little more complicated), why is userEvent doing something different here than what happens in the browser? Is there a workaround?
@testing-library/dom
9.3.4
vitest
1.5.0
jest-environment-jsdom
27.5.1
node
20.12.2
The behavior of
userEvent.click()
is inconsistent with what happens in the browser under the specific condition when IpreventDefault
insideonPointerDown
:If I comment out the problematic line (
e.preventDefault()
), the test passes:If I use
fireEvent
instead ofuserEvent
, it works:If I use
onMouseDown
instead ofonPointerDown
, it's also ok:More importantly, if I put this exact same button on the page and click it (in Chrome 123.0.6312.124), it works fine; the
onClick
fires as expected.So
userEvent.click()
is doing something differently than what seems be happening with the real user interaction.Leaving aside the question of whether the code inside
onPointerDown
is a good idea or not (my real code is a little more complicated), why isuserEvent
doing something different here than what happens in the browser? Is there a workaround?