Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a click outside event?

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>
like image 583
Ever Avatar asked Feb 03 '23 16:02

Ever


2 Answers

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

like image 174
itay oded Avatar answered Feb 06 '23 07:02

itay oded


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

like image 29
Jonathan Irwin Avatar answered Feb 06 '23 09:02

Jonathan Irwin