1

I have issue with react testing library. I write a test case for a modal window open on editor and then close to fire closed event. but on image button click but it does not show the open class as rendered modal in test after click. seems like it find the element before it loads all the classes. here is the link of editor redactor editor You can see it just removed the open class on closing modal window. In my case i never get opened class in my test render component. Below is my test case

it('should open image modal and close ', async () => {
    render(<Editor id='test-modal' initValue={props.initValue} />)
    jest.setTimeout(30000)
    const imageButton = screen.getByLabelText('Image')
    userEvent.click(imageButton.firstChild)
    await waitFor(() => {
      const imageModal = screen.queryByText('Image')
      screen.debug(imageModal.parentNode.parentNode)
    }, { timeout: 4000 })

    // expect(imageModal).toBeInTheDocument()
    // const closeButton = imageModal.previousSibling
    // // userEvent.click(closeButton)

    // screen.debug(closeButton.parentNode.parentNode)
    expect(imageButton.parentNode.parentNode).toHaveClass('redactor-animate-hide1')
  })

1 Answer 1

1

There is a problem with your code snippet, as trying to execute it shows an error message:

{
  "message": "SyntaxError: expected expression, got '<'",
  "filename": "https://stacksnippets.net/js",
  "lineno": 13,
  "colno": 11
}

Nevertheless, I just ran into the same problem as yours when writing tests and thought to share the solution I managed to cobble together.

Rather than use a setTimeout that slows down your test suite, you'll want a Promise that resolves once the CSS class has appeared, and rejects otherwise.

Since jest's matchers throw an error when they don't match, you can catch the error and use it with testing-library's waitFor like below:

await waitFor(() => {
  try {
    expect(imageButton.parentNode.parentNode).toHaveClass('redactor-animate-hide1');
    return Promise.resolve();
  } catch (error) {
    return Promise.reject(error);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.