简体   繁体   English

如何触发点击外部事件?

[英]How to trigger a click outside event?

I'm writing unit testing and e2e testing for a popover component in React.我正在为 React 中的 popover 组件编写单元测试和 e2e 测试。 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.我使用 Jest + Enzyme 进行单元测试,使用 Cypress 进行端到端测试。 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.但是点击的点其实在popup window之外,但是不起作用。 react-tiny-popover library is used to show the popover as follows: react-tiny-popover库用于显示弹出窗口,如下所示:

<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>

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点击参考

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除非您要多次使用它,否则无需添加命令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM