equivalent to soft assertion for locators in playwright

Viewed 15

I have a test that I want to continue even if a locator call fails. I know about soft assertions, and they work as expected for my use case, but is there an equivalent for page.locator().someMethod()?

// test will continue executing past this line if #some-selector doesn't contain 'some text'
expect.soft(page.locator('#some-selector')).toHaveText('some text')

// this button may not exist, but I still want to try clicking it
await page.locator('#may-not-exist').click()

// how can I run this if the line above it fails?
await page.locator('#will-exist').click()

I want the last line of the test to run regardless if either expect.soft fails or if a page.locator invocation fails.

Is there something like page.locator.soft() in Playwright API? I've looked through all the methods and don't see anything like it.

1 Answers

Test test is stopped here: await page.locator('#may-not-exist').click() not at an assertion line.

Because Playwright won't be able to interact with an element that doesn't exist.

if you must click on #will-exist:

expect.soft(page.locator('#some-selector')).toHaveText('some text');
const mayNotExist = await page.locator('#may-not-exist');

if (mayNotExist.isVisible()) {  // checks if locator is visible on DOM
  await mayNotExist.click();
}

await page.locator('#will-exist').click(); // clicks on locator anyway!
Related