I need to test a user that updates the value of a input with type time
and a previous defaultValue
using @testing-library/user-event
in a React component. Why does the following test fail? How can I test this use case?
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
it('should update a value of a time input', async () => {
const user = userEvent.setup();
render(
<label>
Time:
<input type="time" defaultValue="10:30" />
</label>
);
const input = screen.getByLabelText('Time:');
await user.type(input, '06:45');
expect(input).toHaveValue('06:45');
});
This test fails with the following output.
expect(element).toHaveValue(06:45)
Expected the element to have value:
06:45
Received:
10:59
23 | const input = screen.getByLabelText('Time:');
24 | await userEvent.type(input, '06:45');
> 25 | expect(input).toHaveValue('06:45');
| ^
26 | });
How can I update my test to make it succeed?
You can use initialSelectionStart
and initialSelectionEnd
properties.
These properties will clear your input by highlighting all the current text and then replacing it with the new value. This will change the initial value of the input with the new one.
await user.type(input, "06:45", {
initialSelectionStart: 0,
initialSelectionEnd: input.value.length,
});