trigger react-ace onChange via React Testing Library (RTL)
Asked Answered
S

2

7

in my code, i have component that using react-ace. in my render function i have this row:

<CodeEditor onChange={onCodeChanged} value={code} />

callback function:

const onCodeBodyChanged = (newCode) => {
      // some code ...
      dispatch(setResource({ newCode }));
}

I want to test onCodeChanged via RTL, so I tried to find the text area on change the value, but without any success

example of (not working) test:

      const { container } = render(<ResourceEditorPanel />, createMockStore());
      const ace = container.querySelectorAll('.ace_text-input');
      fireEvent.change(ace, { target: { value: 'someText' } });
      await waitFor(() => {
        expect(dispatch).toHaveBeenCalled();
      });

the problem is fireEvent.change(ace, { target: { value: 'someText' } }); doesn't trigger my function - onCodeChanged.

Do you know how can I test it?

Swint answered 25/8, 2020 at 6:1 Comment(0)
P
1

I spent far too much time on this :/ in the end my issue was a small one. The element that should have the data pasted into it is the class "ace_content". The following worked for me.

const editorInputField = container.querySelector('[class="ace_content"]') as Element;

fireEvent.click(editorInputField);

await userEvent.click(editorInputField);
await userEvent.paste('{ "name": "Test" }')
Polly answered 8/9, 2022 at 0:28 Comment(2)
fireEvent.click(editorInputField); was not necessary for me.Gapes
A note to those who come here looking for a solution to their problem, the API of UserEvent.paste has changed in testing-library v14 (from paste(element, text) to paste(text)); make sure to click or focus the element you want to paste into.Twitty
N
-1

Ace editor awaits for an input event so you'll also need to fire something like fireEvent(ace, new Event('input'))

Nitz answered 18/5, 2021 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.