例如,我正在测试一个搜索页面,它将在.text > span:nth-child(1)
中显示结果编号。
但是,如果没有任何结果,则只显示text="nothing"
或.text > span:nth-child(1)
不存在。
那么,我该如何等待这两种情况呢?
您需要使用一个逗号分隔的CSS选择器列表,该列表将匹配该列表中一个选择器可以选择的所有元素:
// ↓ comma
await page.locator('.text > span:nth-child(1), span:has-text("nothing")').innerText();
它将等待.text > span:nth-child(1)
或span:has-text("nothing")
。
您可以等待这两个元素,使用try-catch,并根据找到的元素设置布尔变量。
在Java中,您可以使用类似的东西
Boolean nothingFound, resultsFound = false;
try {
page.waitForSelector("text="nothing"");
nothingFound = true;
} catch (Exception e) {}
try {
page.waitForSelector(".text > span:nth-child(1)");
resultsFound = true;
} catch (Exception e) {}
我不是Javascript专家,但我认为这样的东西应该有效:
let nothingFound, resultsFound = false;
try {
await page.waitForSelector('text="nothing"');
nothingFound = true;
}
catch (e) {}
try {
await page.waitForSelector('.text > span:nth-child(1)');
resultsFound = true;
}
catch (e) {}
如果您需要一个等待两个测试ID中任何一个的解决方案,这是我所知道的唯一解决方案:
/* Note that the `.then` is needed because
* `waitFor` returns `Promise<void>` and we
* can't distinguish which `void` in `element`
* is which `Promise` instance
*/
const element1Promise = page
.getByTestId('testId1')
.waitFor()
.then(() => 'element1');
const element2Promise = page
.getByTestId('testId2')
.waitFor()
.then(() => 'element2');
// Wait for either of the promises to settle
const element = await Promise.race([
element1Promise,
element2Promise,
]);
// Use `element` for conditional logic