How can I test a popover from chakra-ui

1.4k views Asked by At

I need to test a popover from chakra-ui in a React App. I tried with this. But It does not find the popover. If I try by text, then I cannot assert if it is visible.

  it('show a popover when hover terms and conditions', () => {
    render(<SummaryForm />);
    const link = screen.getByText(/terms and conditions/i);

    const popover = screen.getByRole('dialog');

    expect(popover.parentNode).not.toBeVisible();

    userEvent.click(link);

    expect(popover.parentNode).toBeVisible();
  });

3

There are 3 answers

2
Drew Cordano On

try toBeInTheDocument() or toMatchSnapshot()

0
JoeTidee On

The chakra Modal applies a transform style to toggle its visibility. toBeVisible only checks a limited set of style attributes - transform is not one of them - so you might have to check for those instead, for example:

For invisibility:

expect(screen.getByRole('dialog')).toHaveStyle('transform: translateX(0px) translateY(0.18967%) translateZ(0);')

0
Olivier On

Try using the hidden option of the API:

const popover = screen.getByRole('dialog', {hidden: true})

ChakraUI renders a wrapper div around the section that has the dialog role. You can see this by using screen.debug() if you are using the testing-library. Notice the wrapper controls the visibility of said section, which starts as hidden, with styling elements and aria tags.

Using the hidden option allows you to look amognst the elements that aren't visible in the accessibility tree.

Since you want to test the popover, you should know there are some issues with modifying and checking the visibility of the popover when using jest-dom.