Access element whose parent is hidden - cypress.io

前端 未结 6 1325
悲哀的现实
悲哀的现实 2020-12-17 10:38

The question is as given in the title, ie, to access element whose parent is hidden. The problem is that, as per the cypress.io docs :

An element is

6条回答
  •  春和景丽
    2020-12-17 11:04

    I came across this topic but was not able to run your example. So I tried a bit and my final solution is this. maybe someone other also needs this. Please note that I use typescript.

    First: Define a custom command

    Cypress.Commands.add("isVisible", { prevSubject: true}, (p1: string) => {
          cy.get(p1).should((jq: JQuery) => {
            if (!jq || jq.length === 0) {
                //assert.fail(); seems that we must not assetr.fail() otherwise cypress will exit immediately
                return;
            }
    
            const elem: HTMLElement = jq[0];
            const doc: HTMLElement = document.documentElement;
            const pageLeft: number = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
            const pageTop: number = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
            let elementLeft: number;
            let elementTop: number;
            let elementHeight: number;
            let elementWidth: number;
    
            const length: number = elem.getClientRects().length;
    
            if (length > 0) {
                // TODO: select correct border box!!
                elementLeft = elem.getClientRects()[length - 1].left;
                elementTop = elem.getClientRects()[length - 1].top;
                elementWidth = elem.getClientRects()[length - 1].width;
                elementHeight = elem.getClientRects()[length - 1].height;
            }
    
            const val: boolean = !!( 
                elementHeight > 0 && 
                elementWidth > 0 && 
                elem.getClientRects().length > 0 &&
                elementLeft >= pageLeft &&
                elementLeft <= window.outerWidth &&
                elementTop >= pageTop &&
                elementTop <= window.outerHeight
            );
    
            assert.isTrue(val);
          });
    });
    

    Please note the TODO. In my case I was targeting a button which has two border boxes. The first with height and width 0. So i must select the second one. Please adjust this to your needs.

    Second: Use it

    cy.wrap("#some_id_or_other_locator").isVisible();
    

提交回复
热议问题