在 Cypress 中隐藏模式、弹出窗口和叠加层

Hiding modals, popups and overlays in Cypress

我正在为一个网站编写赛普拉斯测试,该网站有多个模式(iframe 内的时事通讯注册)、弹出窗口(“如果 X、Y 和 Z 记得免费送货”)和叠加层。

这些元素是个大问题,因为它不可能 'click field A' 并用文本填写:abcd。由于叠加层在整个事物之上打开。

首要问题:如何摆脱这些模式、弹出窗口和叠加层,以便我可以与页面进行交互?


解决方案尝试 1:在 beforeEach 中注入样式表,使用 display: none;

我想象的是这样的:

cy.get('head').then( (head) => {
  let gottenHead = document.head;
  let styles = document.createElement('style');
  styles.type = 'text/css';
  styles.innerHTML = '.iframes-container { display: none !important; }'
  gottenHead.appendChild( styles ); // Doesnt work, 
  head.appendChild( styles ); // Doesnt work
});

或[这里的要点],但这也不起作用,抛出错误:“无法读取未定义的属性(读取'appendChild')”这一行:doc.body.head.appendChild($style);


解决方案尝试 2:

添加 mutation observer,检查是否有任何包装元素被添加到 dom。如果他们这样做 - 再次删除它们。

这又一次,不像'The Cypress Way'。 所以我还没有尝试过这个。


解决方案尝试 3:弄清楚它们何时打开并单击 'close'

这似乎是最有机的方法。但实际上我宁愿有一个懒惰的选项,只要 Cypress 是 运行.

,它就会将它们全部隐藏起来

但问题在于 'close' 按钮是 inside an iframe, which Cypress doesn't like interacting with


其他信息

我检查了 Cypress' documentation,但没有找到任何关于如何绕过这些模式和弹出窗口的指南,这很奇怪。


Update1: Agoff 问什么跟踪,如果 modal/popups 应该显示。我尝试检查是否设置了 cookie、会话变量或某些本地存储。但是在 'clicking them away' 之后,我看不到添加任何内容。 :-/

删除元素

cy.get('modal-top-element')
  .then($modal => $modal[0].remove)

如果它出现在它自己的 iframe 中(似乎有疑问),请删除 iframe。

最后证明@agoff其实是对的。它被保存在本地存储中。

我写了这些命令来显示、保存和设置 localStorage(使用 cypress-localstorage-commands package):

在命令中:

import "cypress-localstorage-commands"

Cypress.Commands.add( "displayPopupLocalStorage", () => {
  cy.getLocalStorage('THECUSTOMLOCALSTORAGEKEY').then( (localStorageContents) => {
    cy.log( "THECUSTOMLOCALSTORAGEKEY contents: ");
    cy.log( localStorageContents );
  })
});


Cypress.Commands.add( "savePopupLocalStorage", () => {
  cy.getLocalStorage('THECUSTOMLOCALSTORAGEKEY').then( (localStorageContents) => {
    cy.writeFile( "cypress/fixtures/tmp/popup-local-storage.json", localStorageContents );
  })
});


Cypress.Commands.add( "setPopupLocalStorage", () => {
  cy.fixture( "tmp/popup-local-storage.json", 'utf8' )
  .then( (localStorageContents) => {
    cy.setLocalStorage('THECUSTOMLOCALSTORAGEKEY', JSON.stringify( localStorageContents ) );
  });
});

测试

  it( 'Accept and save pop-up cookies', () => {
    cy.visit( "https://example.org" );

    // Close popup and save local storage
    cy.get( '.popup-wrapper .close-form' ).click()
    cy.wait( 500 ); // Needed for the animation to finish, so the localStorage is set
    cy.savePopupLocalStorage();
  });


  it( 'Sets popup cookies and check that header is clickable', () => {
    cy.setPopupLocalStorage();
    cy.visit( "https://example.org" );
    cy.get('.popup-wrapper', { timeout: 10000 }).should('not.exist');

    // Verify that it works, by going to a page and ensure that the something is clickable
    cy.get( '#header .logo > a' ).then( ($logo) => {
      Cypress.dom.isFocusable( $logo );
    });
  });