← Back to Discord Forum

expect vs. wait

I have a mysteriously failing test, and I have some suspicion. Am I right that if there is some element on the page which is hidden (via display: none) and it's shown after some time (less than the timeout, but still), then await expect(locator).toBeVisible(); will (may?) fail, but await locator.waitFor({state: 'visible'}); will work? Also, do I get it right that if I use the latter, there's no need to assert the visibility of that element after that?

This thread is trying to answer question "What is the difference between using expect and waitFor to check if an element is visible, and will expect fail if the element is hidden at first?"

12 replies

Also, do I get it right that if I use the latter, there's no need to assert the visibility of that element after that? Either assertion guarantee that the locator was visible at that point, but the page/app under test can very well hide/delete it soon after.

Understood, but what if the element is hidden at the moment the above code runs? Will the former assertion fail, because the element is found but not visible?

Yes, it will fail if the element isn't visible within the timeout. You can adjust the timeout by passing an optional argument to the the waitFor(...) or toBeVisible(...)

the timeout is 5 seconds by default, and in my case the element becomes visible much faster

so my suspicion was that expect(locator).toBeVisible(); fails because the element is found, but not visible

if it were not present, but appeared within 5s, then the timeout magic would do its thing and the assertion would pass

but does that assertion wait 5s if the elemebt is present but hidden at first?

Did you record a trace and dug through it to see the state of the locator ? Or added an await page.pause() to break your test and debug it manually from there ?

the waitFor(...) and toBeVisible(...) check several times, and eventually succeed within 5s or fail after 5s

page.pause() won't help me – my tests run on a machine w/o an input device and monitor, I can only ssh into it

I did record a trace, but it didn't help at all – the element that PW claimed to be "hidden" was visible on the trace "screenshot", and marked blue (as the selected one, I guess)

if I run the test locally on my laptop, it passes ok

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.