Trouble on testing onChange property from ant design

Viewed 487

I’m having trouble in testing the behaviour of an ant design component.

I use Text component from ant design with ‘editable’ and ‘onChange’ properties for editing a comment. For saving the new content I have to click anywhere on the page or to press enter and the onChange function will be triggered. I tested manually and everything works fine.

In tests, I manage to edit the content of the comment, but when I simulate the enter pressing (or the clicking on any DOM element) the onChange function is not called. What should I do in order to trigger the onChange function?

Here's my component:

<Text editable={{ onChange: editComment }}
  id={"edit-comment-" + props.commentIndex}>
  {props.body}
</Text>

Here's my test:

the test includes both methods of triggering the onChange function, but I did not use both of them at the same time

test('Edit comment request', async () => {
  const fakeResponse = {
    success: 1
  };

  jest.spyOn(global, "fetch").mockImplementation(() =>
    Promise.resolve({
      json: () => Promise.resolve(fakeResponse)
    })
  );

  const editButton = container.querySelector("span[aria-label='edit']");
  await fireEvent.click(editButton);

  // Edit the comment content
  fireEvent.change(screen.getByRole('textbox'), { target: { value: "edited comment" } });

  // Save the comment content by pressing enter
  await fireEvent.keyPress(screen.queryByText(/edited comment/i),
    { key: "Enter", code: "Enter", keyCode:13, charCode: 13 });

  // Save the comment content by clicking on a random DOM element
  await fireEvent.click(container.querySelector('.ant-comment-content-author'));

  await wait(() => expect(global.fetch).toHaveBeenCalled());
});
1 Answers

Try to set _defaultValue property before dispatch the onChange event:

const textbox = screen.getByRole('textbox');
textbox.value =  "edited comment";
textbox._valueTracker.setValue(null);
fireEvent.change(textbox, {bubbles: true});

To React the value is still unchanged. Check this issue: https://github.com/facebook/react/issues/11488

Related