Search code examples
javascripthtmlautomated-testsplaywright

How to assert a HTML element is valid link in Playwright?


I'm trying to do some assertions in Playwright. I need to assert that in a list of links <a> all of them have the attribute href. However, I don't know how to achieve that with Playwright functions.

My code is here:

test.only('then a list of 44 links is displayed', async({ page }) => {
         const linkList = await page.locator('div#content > ul > li > a');
         for(let i = 0; i < await linkList.count(); i++) {
             expect(await linkList.nth(i)).toHaveAttribute('href', '');             }
         await expect(linkList).toHaveCount(44);
    })

toHaveAttribute() function need 2 to 3 arguments because it get the key attribute and the value of the attribute, but I need just to check if it has the href attr.

How can I achieve that?

This is the website being tested: https://the-internet.herokuapp.com/


Solution

  • After trying some options, I realize that I can assert if when using Locator.getAttribute('href') does not return null, so that's a link. So I implemented that:

    const linkList = await page.locator('div#content > ul > li > a');
    for(let i = 0; i < await linkList.count(); i++) {
        expect(await linkList.nth(i).getAttribute('href')).not.toBeNull();
    }