0

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?

Mirco Bellagamba
  • 950
  • 6
  • 15

1 Answers1

2

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,
});
Pluto
  • 4,177
  • 1
  • 3
  • 25
  • 1
    Thanks, that works! However it seems a bit weird because the user does not select anything in a real browser. Anyway, this could be acceptable considering that the `` is not fully implemented in `js-dom`. – Mirco Bellagamba Jul 13 '23 at 13:54
  • You're welcome. I'm glad it works for you. I agree that it is a bit weird, but it is a workaround for the limitation of js-dom. Maybe in the future, js-dom will support better and you won't need this hack. – Pluto Jul 13 '23 at 13:57