#Day97 of #100daysofcode
Today I learned how to emulate certain user interaction events that don’t have a dedicated method (like mouseover). Rather than use button.click()
.
To overcome this we can dispatchEvent API, here’s how it works.
// First, we will create a mouse click event using the MouseEvent interface
const incrementClickEvent = new MouseEvent('click', {
bubbles: true,
cancelable: true,
button: 0,
})
// Now we can simply utilise the above event in our increment button's dispatch event,
// which will trigger the incrementClickEvent whenever it gets clicked.
act(() => increment.dispatchEvent(incrementClickEvent))
We have seen how to test React components by emulating the component render and UI interactions, but that comes with a lot of boilerplate, let’s take a look at how React Testing Library by Kent C Dodds can improve the developer experience and help us reduce the boilerplate:
import * as React from 'react'
import {render, fireEvent} from '@testing-library/react'
import Counter from '../../components/counter'
test('counter increments and decrements when the buttons are clicked', () => {
const {container} = render(<Counter />)
const [decrement, increment] = container.querySelectorAll('button')
const message = container.firstChild.querySelector('div')
expect(message).toHaveTextContent('Current count: 0')
fireEvent.click(increment)
expect(message).toHaveTextContent('Current count: 1')
fireEvent.click(decrement)
expect(message).toHaveTextContent('Current count: 0')
})