javascriptreactjsreact-testing-libraryuser-event

How to replace value of input with userEvent in react jest test


When using userEvent.type in react the value is appended to the current inputs value. How can I replace the current value / clear the input using userEvent?

I have tried to use {backspace} and {selectall} tokens but they have no effect. Do I have to manually reset the inputs value?

await userEvent.type(input, "1"); // 1
await userEvent.type(input, "123"); // 1123

// I can manually reset value using .value setter though
input.value = "";
await userEvent.type(input, "123"); // 123

Solution

  • Selects the text inside an input or textarea and deletes it.

    https://testing-library.com/docs/ecosystem-user-event/#clearelement

    await userEvent.clear(input);