Search code examples
reactjsreact-testing-library

Testing react-contenteditable with react testing library


How to test this component: https://github.com/lovasoa/react-contenteditable? How to mimic user action in test environment? I've tried following:

// The given element does not have a value setter
fireEvent.change(sourceContent, {
  target: { value: "New content text" }
});

// This doesn't emit onChange Changes text content but onChange is not fired.
fireEvent.change(sourceContent, {
  target: { textContent: "New content text" }
});

// This doesn't emit onChange. Changes inner html but onChange is not fired.
fireEvent.change(sourceContent, {
  target: { innerHTML: "New content text" }
});

All of the above are failed tests. I thought that if I change innerHTML then function provided in onChange will be fired. This is sample project with this problem: https://codesandbox.io/s/ecstatic-bush-m42hw?fontsize=14&hidenavigation=1&theme=dark


Solution

  • With https://github.com/testing-library/user-event/issues/442 fixed, it's now possible with userEvent:

    const element = screen.getByTestId("myEditableElement");
    await userEvent.click(element);
    await userEvent.keyboard("abc");
    expect(element.textContent).toBe("abc");