katch
katch

Reputation: 930

Element not visible after navigating using playwright

I am using playwright to do my browser automation.

I click a hyperlink which takes me to Google.com and there I want to verify "Google Search" button exists after navigation. Here is my code.

const textToClick = "Visit Google"
const textToVerify = "Google Search"
const elements = await page.$$(`text=${textToClick}`)
await element[0].click()
const elements = await page.$$(`text=${textToVerify}`)
const elementLength = elements.length
console.log("Element Length::",elementLength, ":: TexToFind::",textToVerify)

When I run it with mocha test, "Google Search" button is not found.

But when I run same code through visual studio debugger under node's main entry file(main.js); I am able to find "Google Search" button.

Here is playwright debugger's output from mocha test run:

pw:api => page.goto started +0ms
pw:api navigating to "file:///C:/devel/devspace/js/myAutomation/test/src/sampleApp.html", waiting until "load" [] +3ms
pw:api navigated to "file:///C:/devel/devspace/js/myAutomation/test/src/sampleApp.html" [] +348ms
pw:api "domcontentloaded" event fired [] +7ms
pw:api "load" event fired [] +276ms
pw:api <= page.goto succeeded +6ms
pw:api => elementHandle.click started +364ms
pw:api attempting elementHandle.click action [] +2ms
pw:api waiting for element to be visible, enabled and not moving [] +2ms
pw:api element is visible, enabled and does not move [] +479ms
pw:api scrolling into view if needed [] +1ms
pw:api done scrolling [] +63ms
pw:api checking that element receives pointer events at (358.64,558.1) [] +66ms
pw:api element does receive pointer events [] +188ms
pw:api performing elementHandle.click action [] +2ms
pw:api elementHandle.click action done [] +83ms
pw:api waiting for scheduled navigations to finish [] +3ms
pw:api navigated to "https://www.google.com/" [] +293ms
pw:api navigations have finished [] +46ms
pw:api <= elementHandle.click succeeded +2ms
sleeping
sleeping finished
element Length:: 0 :: TexToFind:: Google Search
1) Test Click Functionality on Hyperlink

You will notice element Length is zero indicating "Google Search" button is not found

What is with mocha test that makes the element not searchable or is there something fundamental thing related to hyperlinks that needs to be handled when verifying elements after hyperlink click takes you to new webpage?

Upvotes: 4

Views: 9346

Answers (1)

hardkoded
hardkoded

Reputation: 21695

The click on the first link will cause a navigation. So you need to wait for the page to navigate to Google. You can do something like this:

await Promise.all([elements[0].click(), page.waitForNavigation()]);

Upvotes: 2

Related Questions