What is the difference between testing the click of a button by triggering it with element.click
vs fireEvent.click
(RTL doc).
Here an example:
import { expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
function SampleComponent({ callback }: { callback: () => void }) {
return (
<div>
<button onClick={() => callback()}>Do something</button>
</div>
)
}
describe('Component', () => {
it('element.click', () => { //Green
const callback = vi.fn()
render(<SampleComponent callback={callback} />)
screen.getByRole('button').click()
expect(callback).toHaveBeenCalledTimes(1)
})
it('fireEvent.click', () => { //Green as well
const callback = vi.fn()
render(<SampleComponent callback={callback} />)
fireEvent.click(screen.getByRole('button'))
expect(callback).toHaveBeenCalledTimes(1)
})
})
Initially, I thought that the element.click
was just a plain invocation of the method, and therefore I thought all the logic related to the event bubbling was missing.
But now I'm confused because even if I move the callback on the parent both scenario seems to pass.
import { expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
function SampleComponent({ callback }: { callback: () => void }) {
return (
<div onClick={() => callback()}>
<button>Do something</button>
</div>
)
}
describe('Component', () => {
//same tests as before - Both green
})
So what's the difference, which one should be used and why?
Thx