简体   繁体   English

遍历DOM以选择特定子级进行e2e测试

[英]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. 对于我的Angular应用程序,我正在编写一个简单的脚本来测试两个按钮的功能。 The html looks like so: HTML看起来像这样:

<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. 因为我没有两个按钮的CSS选择器ID或类,所以需要遍历DOM才能单击它们。 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. 在这种情况下,遍历DOM并单击特定按钮上的最简单/最干净的方法是什么。

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. 因此基于给定的DOM结构。 The following will be the code snippet that will return you the btn elements 以下是将返回btn元素的代码段

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();

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

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