简体   繁体   中英

Traverse DOM to select specific child for e2e test

For my Angular application I am writing a simple script to test functionality of two buttons. The html looks like so:

<body>

   <my-app _nghost-c0 ng-version="4.46">
     <mat-card _ngcontent-c) class="overflow mat-card">
       <div _ngcontent-c) class="login">...</div>
       <div _ngcontent-c) float-right>
         <button _ngcontent-c0> List Button </button>
         <button _ngcontent-c0> User Button </button>
       </div>
     </mat-card>
...
</body>

Because I do not have a CSS selector Id or Class for the two buttons I need to traverse the DOM to click them. I have tried the following:

await page.evaluate(() => {
    document.getElementsByClassName('login').children('button').click();
});

The issue with this approach is that it cannot find the node and in fact it has no way to find the specific button of 'List Button' or 'User Button'. What is the simplest/cleanest way to traverse the DOM and click() on a specific button in this case.

You are trying to find the children in the wrong parent element. You need to find the children in the element next to the login class. So based on the given DOM structure. The following will be the code snippet that will return you the btn elements

var loginElement = document.querySelectorAll('.login')[0];
var listBtn = loginElement.nextElementSibling.children[0];
var userBtn = loginElement.nextElementSibling.children[1];    

listBtn.addEventListener("click",function(){
 console.log('listBtn clicked');
})

userBtn.addEventListener("click",function(){
 console.log('userBtn clicked');
})

listBtn.click();
userBtn.click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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