Test a textbox with testing library

Last updated June 22, 2021 by Jacob Paris

These examples are built with the following opinion:

A textbox loads immediately with the correct value

There is no interaction needed here, just finding the input and reading its value

js
1const usernameInput = screen.fetchByRole('textbox', {
2 name: 'Username',
3})
4
5expect(usernameInput).toHaveValue('Alice')
6

Test succeeded!

A textbox appears immediately and eventually loads the correct value

If the value for the textbox comes from a server, there might be time where the input has appeared before its value has loaded. Consider whether this is intended behaviour, or if the component should wait until its data is ready before loading at all.

js
1const usernameInput = screen.fetchByRole('textbox', {
2 name: 'Username',
3})
4
5await waitFor(() => {
6 expect(usernameInput).toHaveValue('Alice')
7})
8

Test failed

A textbox will eventually appear with the correct value

If the textbox is not initially on the screen, for example if the user opens up a form, we might need to wait for the textbox itself to appear.

js
1const usernameInput = await screen.fetchByRoleAsync('textbox', {
2 name: 'Username',
3})
4
5expect(usernameInput).toHaveValue('Alice')
6

Test failed

A textbox was updated by a user

If a textbox has been updated by user interaction, we can test its value directly.

js
1const usernameInput = screen.fetchByRole('textbox', {
2 name: 'Username',
3})
4
5userEvent.type(usernameInput, 'Alice')
6
7expect(usernameInput).toHaveValue('Alice')
8

Test failed