saylestyler
saylestyler

Reputation: 469

equivalent to soft assertion for locators in playwright

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.

Upvotes: 3

Views: 1509

Answers (2)

Pablorotten
Pablorotten

Reputation: 103

You can wrap the error-prone lines with a try/catch block:

try {
  await page.locator('#may-not-exist').click()
} catch (error) {
  console.warn('Could not click on #may-not-exist, test will continue:', error);
}

The test will continue and you'll find in the log if the click() actually failed o not.

Upvotes: 0

jkalandarov
jkalandarov

Reputation: 685

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 you can write this:

expect.soft(page.locator('#some-selector')).toHaveText('some text');

const mayNotExist = await page.locator('#may-not-exist');
// checks if locator is visible on DOM
if (mayNotExist.isVisible()) 
{  
  await mayNotExist.click();
}

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

Upvotes: 3

Related Questions