How to trigger a click outside event?
Asked Answered
N

2

21

I'm writing unit testing and e2e testing for a popover component in React. I should check if the popup is hidden when I click outside the component. I'm using Jest + Enzyme for unit testing and Cypress for e2e testing. Does anybody know how to do this?

I've tried as follows in cypress.

cy.get('[data-test-id="popover-container"]').click(-20, -20, {force: true});

But the clicked point is actually outside of the popup window, but it doesn't work. react-tiny-popover library is used to show the popover as follows:

<Popover
      content={({ position, targetRect, popoverRect }) => (
        <ArrowContainer
          position={position}
          targetRect={targetRect}
          popoverRect={popoverRect}
          arrowColor={'#ccc'}
          arrowSize={10}
        >
          <div data-test-id="popover-container">
            <Content/>
          </div>
        </ArrowContainer>
      )}
      isOpen={visible}
      onClickOutside={() => hideOnOutsideClick && setVisible(false)}
      position={position}
    >
      <div onClick={() => setVisible(!visible)}>{children}</div>
    </Popover>
Nowhither answered 28/10, 2019 at 15:12 Comment(3)
why don't you select an element that you know is outside of the popover-container and click it?Faldstool
I tried it already and it's working. But not sure what is the best practise.Nowhither
And also, how to do it in unit testing with Jest and Enzyme?Nowhither
H
34

You can simply click somewhere on the body:

Cypress.Commands.add('clickOutside', function(): Chainable<any> {
  return cy.get('body').click(0,0); //0,0 here are the x and y coordinates
});

In test:

cy.get('[data-test-id="popover-container"]').clickOutside();

click reference

Hexastyle answered 4/1, 2021 at 10:34 Comment(0)
A
13

Taken from the other answer you can just:

cy.get('body').click(0,0);

No need to add a command unless you are going to use it many times

Ames answered 28/9, 2021 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.