我是在 Protractor 中编写 e2e 测试的新手。 我开始在 Protractor 测试中使用异步等待,并添加浏览器等待。下面是我的代码。 问题是 Protractor 从未找到 menuBtn 并且超时。我尝试使用 visilityOf 和 PresenceOf 的 ExpectedCOnditions。但它们都卡在那里,永远不会得到解决。 我以为我给出了错误的定位器。但是,当使用 $x('xPath on line 3') 时,它会在网页上检测到它。 有人可以帮忙解决这个问题吗?
async menuNav(title, pageElement) {
browser.sleep(3000);
// browser.waitForAngular();
const menuBtn = element(by.xpath('.//mat-icon[@id="' + pageElement + '"]'));
console.log('menu btn: ', menuBtn.locator());
await browser.wait(() => {
return browser.isElementPresent(menuBtn);
}, 3000);
await menuBtn[0].click();
const menuTitle = element(by.xpath('.//*[contains(text(),\'' + title + '\')]'));
browser.sleep(3000);
menuTitle.isPresent().then(result => {
expect(result).toBe(true);
console.log('inside is present');
console.log(title);
});
}
这就是 HTML 的样子
<div *ngFor="let item of items"
class="item"
placement="right"
container="body"
containerClass="sidebar-tooltip">
<mat-icon class="icon" [id]="item.id" [svgIcon]="item.icon"></mat-icon>
</div>
根据@Gunderson 和@SimonN 的评论,我在元素定位器之前添加了await。但我认为它们只是定义,因为我没有使用像 findByElement 这样的 Protractor 定位器。但是我更改了代码,它仍然在 menuBtn.click 处阻塞,现在这是我的代码:
async menuNav(title, pageElement) {
browser.sleep(3000)
const menuBtn = await element(by.xpath('.//mat-icon[@id="' + pageElement + '"]'));
browser.wait(() => {
return browser.isElementPresent(menuBtn);
}, 3000);
return menuBtn.isPresent().then(elementAvailable => {
browser.wait(this.EC.elementToBeClickable(menuBtn), 3000).then(async () => {
await menuBtn.click();
const menuTitle = await element(by.xpath('.//*[contains(text(),\'' + title + '")]'));
return browser.wait(this.EC.presenceOf(menuTitle), 3000).then(() => {
return true;
});
});
}).catch(error => {
console.log('error: ', error);
});
}
最佳答案
@yong 的评论是正确的,你在很多地方都缺少 await
。它需要位于所有 Protractor 函数(包括定位器)的前面。你也不应该需要任何 sleep ,但我现在就把它们留在那里:
async menuNav(title, pageElement) {
await browser.sleep(3000); <-- missed await here
const menuBtn = await element(by.xpath('.//mat-icon[@id="' + pageElement + '"]')); <-- missed await here
await menuBtn[0].click(); <-- this isn't an ElementArray, so not sure why [0] is there
const menuTitle = await element(by.xpath('.//*[contains(text(),\'' + title + '\')]')); <-- missed await here
await browser.sleep(3000); <-- missed await here
// no need to use .then() here either
expect(await menuTitle.isPresent()).toBe(true);
}
关于angular - Protractor 测试中的异步/等待逻辑未检测到页面元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54138893/