`userEvent.type` with selection range behaves unexpectedly when run in a browser
See original GitHub issueHello again 👋 I’m seeing inconsistent behavior with userEvent.type
being run in the test vs. in the browser outside of the test. For some reason, the typing with selection range example from the docs works in the JS test runner, but doesn’t work in the actual browser.
@testing-library/user-event
version: 13.1.8@testing-library/react
version: 11.2.5
Relevant code or config
import React from “react”;
import { render, screen } from “@testing-library/react”;
import userEvent from “@testing-library/user-event”;
render(
<div>
<label htmlFor=“my-input”>Example:</label>
<input id=“my-input” type=“text” defaultValue=“This is a bad example” />
</div>
);
const input = screen.getByLabelText(/example/i);
input.setSelectionRange(10, 13);
userEvent.type(input, “good”);
What I did: I took the userEvent.type with selection range example from the docs and ran it in a js file outside a test.
What happened:
The resulting input value was supposed to be "this is a good example"
, but instead it was "doothis is a g example"
:
Reproduction repository:
Suggested solution:
Based on stepping through the debugger, I think the issue is related to these lines in setSelectionRange
. It seems like selection.addRange(range)
might not be working as expected so then selection range is cleared to zero after selection.removeAllRanges()
. I’m not sure how to solve this though.
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
🎉 This issue has been resolved in version 13.1.9 🎉
The release is available on:
npm package (@latest dist-tag)
Your semantic-release bot 📦🚀
Thanks a lot for the report. ❤️
It looks like our implementation is based on a false premise. If you select inside the input, the browser sets the selection on the parent
<div>
.When you type into the input, the selection range is not changed at all.
https://codesandbox.io/s/rtl-selection-range-example-forked-221xl?file=/src/App.js
We should skip setting the range on
Selection
for<input>
and<textarea>
.