Locator page.locator(‘.inner-blocks div.img-block’) returns 3 images. I want to verify one by one that all three images are visible on the Page. I am using Page Object Pattern. My page Object class looks like this
Dashboard.js
class dashboardPage{
constructor(page)
{
this.ImageBlocks = page.locator('.inner-blocks div.img-block')
}
async verifytopSectionThreeBlocks()
{
const totalblocks = await this.ImageBlocks.count()
console.log("total count:"+totalblocks)
for(let i=0;i<totalblocks;i++)
{
return (await this.ImageBlocks.nth(i))
}
}
}
module.exports ={dashboardPage};
And in the test class i am trying to assert that all images are visible.
const result = dashboardpage.verifytopSectionThreeBlocks()
await except (result).toBeVisible()
This is giving error. Could anyone point it out and fix what is wrong here.
2
Answers
You wrote the loop with a return statement; however, functions can only return one value. This means that your loop will perform only one iteration and stop afterward because the function’s execution will conclude. As a result, you will always receive only the first image.
Try running this code to confirm:
To check all images, you can modify the code to return an array of images. Then, within the test, you can iterate through the array to perform the necessary checks.
This answer has the right idea, but is missing
.all()
:In a POM:
A few notes:
return
ends the function, breaking the loop at the first iteration.count()
/nth()
.except
should beexpect
.this.ImageBlocks
should be camelCase instead of UpperPascalCase, sothis.imageBlocks
.verifytopSectionThreeBlocks
doesn’t actually verify anything, just retrieves locators. I’d call ittopSectionBlocks
or similar.