Skip to content

Selection-related target properties not set in fired events #263

@diego-codes

Description

@diego-codes
  • dom-testing-library version: 4.0.1
  • react version: 16.8.6
  • node version: 11.7.0
  • npm version: 6.9.0

Relevant code or config:

test('auto-matches matchable characters', () => {
  const onChange = jest.fn();
  const { getByTestId } = render(<Textarea onChange={onChange} />);
  
  fireEvent.change(getByTestId('input'), {
    target: { value: '[', selectionStart: 1, selectionEnd: 1 },
  });

  expect(onChange).toHaveBeenCalledWith('[]');
});

What you did:

I am attempting to test an input component that relies on the text cursor position when a value changes for a character auto-matching feature. I fire a change event with a target value, selectionStart, and selectionEnd to simulate a user adding a single character that moves the text cursor position forward by one.

What happened:

The event target values for selectionStart and selectionEnd are not making it to the change event handler. They are both 0 instead.

Reproduction:

Please check out this code sandbox: https://codesandbox.io/s/reacttestinglibrary-demo-6btmr

I have some tests showing that no variation of firing a change event successfully captures the desired target's selectionStart and selectionEnd values.

In addition, I have some tests that manually update the textarea element's selectionStart and selectionEnd in a variety of ways to demonstrate that it is not a jsdom implementation bug.

Problem description:

According to the documentation, all properties added to the target object will be added to the event target which is then used to call the relevant handlers:

As a convenience, if you provide a target property in the eventProperties (second argument), then those properties will be assigned to the node which is receiving the event.

This is not actually happening for selection-related properties and the type of tests outlined above and in the code sandbox are impossible to run.

Suggested solution:

I think the issue stems from the placement of the line that copies all targetProperties over to the node in https://github.com/testing-library/dom-testing-library/blob/master/src/events.js#L319.

Setting the native value might be overriding the selection-related values and I believe the solution is to move the Object.assign line after the the value and file properties have been assigned.

I've tested this change and my solution works in my project. I'm happy to create a PR with this solution.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is neededreleased

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions