Skip to content

Problems with custom input types #501

@kserjey

Description

@kserjey
  • @testing-library/user-event version: 12.2.2
  • Testing Framework and version: CodeSandbox (actually I don't know how to get it)
  • DOM Environment: CodeSandbox (actually I don't know how to get it)

Relevant code or config:

const { getByRole } = render(<input type="number"/>);
const input = getByRole('spinbutton');
userEvent.type(input, '123{selectall}{backspace}');

Reproduction repository:

https://codesandbox.io/s/user-event-and-typenumber-c5i10

Problem description:

After spending some time trying to solve this issue I've found what causing it. JSDOM has a limitation on setSelectionRange:

https://github.com/jsdom/jsdom/blob/c2fb8ff94917a4d45e2398543f5dd2a8fed0bdab/lib/jsdom/living/nodes/HTMLInputElement-impl.js#L45

And you have a little hack to make it work with userEvent.clear:

user-event/src/clear.js

Lines 12 to 27 in f7620ab

// TODO: track the selection range ourselves so we don't have to do this input "type" trickery
// just like cypress does: https://github.com/cypress-io/cypress/blob/8d7f1a0bedc3c45a2ebf1ff50324b34129fdc683/packages/driver/src/dom/selection.ts#L16-L37
const elementType = element.type
// type is a readonly property on textarea, so check if element is an input before trying to modify it
if (element.tagName === 'INPUT') {
// setSelectionRange is not supported on certain types of inputs, e.g. "number" or "email"
element.type = 'text'
}
type(element, '{selectall}{del}', {
delay: 0,
initialSelectionStart: element.selectionStart,
initialSelectionEnd: element.selectionEnd,
})
if (element.tagName === 'INPUT') {
element.type = elementType
}

But if we are talking about type actions like {selectall}, well, it doesn't work for types other than ["text", "search", "url", "tel", "password"]. For now I'm just using:

const { getByRole } = render(<input type="number"/>);
const input = getByRole('spinbutton');
userEvent.type(input, '123');
userEvent.clear(input);

When I tried to move your hack to the type.js, I faced problems with testing (I can't test selectionStart, because it null) and I wasn't sure how to temporary change element.type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingreleased

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions