Detecting elements exist or do not exist

In an attempt to test logging into our app as different users/roles, different ui elements will be present. I cannot seem to find a good way to determine a selector is null or invalid without throwing an exception. Is there a best practice or recommendation to follow?

1 Like

Hi @jkdale,

You can use the Chrome Dev Tools if you’re using Chrome to find your selectors. This video could help.

Thanks.

That doesn’t appear to be the answer to the original question, which I need an answer to!

If you have some code:

    const locator= page.locator( 'select#someid');
    if (locator.isVisible()) {
        ... do some stuff ...
    }

The problem with the code above is it will throw an exception after waiting 30 seconds to find the element. I could add a try/catch to deal with it but that is ugly and verbose. What is the most terse reliable way to check if an element is present before attempting to reference it in any way?

ChatGPT suggests:

const isElementPresent = await page.evaluate(() => 
 Boolean(document.querySelector('select#someId'));
);

Still seems a bit clunky, feels like there must be a better way.

Hi, welcome!

Have you tried using isVisible() | Grafana k6 documentation? Make sure using the latest k6.

Thanks @inancgumus , yes, just as my example shows - if the component isn’t present on the page it will wait around 30 seconds and then throw an exception rather than return a boolean true/false.

Sure, what is the k6 version you’re using?

v0.48.0 at the moment, can upgrade if there is something good to be had

Yes, the new version should be fixing this issue. Please give it a try and let us know. Thanks!

1 Like

Ah, I see, just seen the release notes for 0.49 - that looks like the change I was looking for (no more 30 second waits) and I LOVE the new dashboard!

1 Like

Thanks! Great to hear!