【问题标题】:How to trigger a click outside event?如何触发外部点击事件?
【发布时间】:2019-10-28 15:12:43
【问题描述】:

我正在为 React 中的弹出框组件编写单元测试和 e2e 测试。 当我在组件外部单击时,我应该检查弹出窗口是否隐藏。 我使用 Jest + Enzyme 进行单元测试,使用 Cypress 进行 e2e 测试。 有人知道怎么做吗?

我在 cypress 中尝试如下。

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

但是点击的点其实是在弹窗之外,但是不起作用。 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>

【问题讨论】:

  • 你为什么不选择一个你知道在popover-container之外的元素并点击它?
  • 我已经尝试过了,它正在工作。但不确定最佳做法是什么。
  • 还有,如何在 Jest 和 Enzyme 的单元测试中做到这一点?

标签: javascript click mouseevent cypress


【解决方案1】:

你可以简单地点击身体的某个地方:

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

测试中:

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

click reference

【讨论】:

    【解决方案2】:

    取自另一个答案,您可以:

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

    除非要多次使用,否则无需添加命令

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2011-01-23
      • 2018-11-23
      • 2018-06-18
      相关资源
      最近更新 更多