#Day98 of 100daysofcode
Today I learned that, in any software, we should avoid testing implementation details of our components. Because the implementation of our abstractions does not matter to the users, we will test our component in such a way that it feels like an actual user is interacting with our application totally unaware of the internals.
Now, instead of getting the DOM node reference like this:
We will utilize the accessibility tree to get the Role and Name of the element rendered to the screen. Let’s take a look at the accessibility pane to understand how we can access the “Increment” button from the screen utility provided by the React Testing Library:
// Getting the increment button by specifying the role as `button` and regex matching the name of the button.
const increment = screen.getByRole('button', {name: /increment/i})
const decrement = screen.getByRole('button', {name: /decrement/i})
// Getting the message text's DOM node reference by regex matching the inner text.
const message = screen.getByText(/current count/i)
I also learned how to test forms and form submissions in React:
test('submitting the form calls onSubmit with username and password', async () => {
const handleSubmit = jest.fn()
render(<Login onSubmit={handleSubmit} />)
const username = 'chucknorris'
const password = 'i need no password'
await userEvent.type(screen.getByLabelText(/username/i), username)
await userEvent.type(screen.getByLabelText(/password/i), password)
await userEvent.click(screen.getByRole('button', {name: /submit/i}))
expect(handleSubmit).toHaveBeenCalledWith({
username,
password,
})
expect(handleSubmit).toHaveBeenCalledTimes(1)
})