How to wait for multiple selectors?

Viewed 1665

For example, I'm testing a search page, which will show the result numbers in .text > span:nth-child(1).

However, if not any result, it will only show text="nothing" or .text > span:nth-child(1) is not exist.

So how can I wait for both conditions?

2 Answers

You need to use a comma-separated list of CSS selectors wich will match all elements that can be selected by one of the selectors in that list:

//                                           ↓ comma
await page.locator('.text > span:nth-child(1), span:has-text("nothing")').innerText();

It will wait for either .text > span:nth-child(1) or span:has-text("nothing").

You can wait for both elements, using a try-catch, and setting a boolean variable, depending on which element is being found.

In Java you could use something like

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) {}

I'm not a Javascript expert, but I think something like this should work:

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) {}
Related