'Testing onClose callback which is triggered by clicking outside component
The popup has a click away listener which closes it when a click event occurs outside the component. I need to test that the popup has closed.
it.only('clicking outside popover calls on close callback ', async () => {
const onCloseCallback = jest.fn();
const { queryByTestId, getByTestId, getByLabelText } = render(
<Popup
onClose={onCloseCallback}
/>
);
fireEvent.click(document);
await waitFor(() => {
expect(queryByTestId('Popup')).toBeNull();
expect(onCloseCallback).toHaveBeenCalledTimes(1);
});
});
The Popup.tsx component
<Popper
open={open}
anchorEl={anchorEl}
data-testid="Popup"
placement="bottom-end"
modifiers={{
arrow: {
enabled: true,
ref: arrowRef
},
flip: {
enabled: false
}
}}>
<span className={classes.arrow} ref={arrowRef} />
<ClickAwayListener onClickAway={handleClose}>
{children}
</ClickAwayListener>
</Popper>
Solution 1:[1]
I am not sure why. But I turned out make it work with
test("When click on cart, should show cart popover, click somewhere should close cart popover", async () => {
// const popoverCart = screen.getByTestId("popoverCart");
// expect(popoverCart).not.toBeInTheDocument();
fireEvent.click(cart);
expect(screen.getByRole("popoverCart")).toBeInTheDocument();
//Click again to close cart
fireEvent.click(window);
await waitFor(() =>
expect(screen.queryByRole("popoverCart")).not.toBeVisible()
);
// expect(queryByTestId(/popoverCart/i)).toBeNull()
});
Just a reference you guys.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kai021195 |