3 types of playwright assertions with different results

180 Views Asked by At

I have the following lines of code. They are 3 different types of assertions that check for the same thing

await page.getByText('Thank you for your purchase!', { exact: true }).isVisible();
await expect (page.getByText('Thank you for your purchase!', { exact: true }).isVisible());
expect(page.getByText('Thank you for your purchase!', { exact: true })).toBeVisible();

The first assertion works perfectly fine. The second one will display an error: expect: Property 'then' not found. If i remove "await" , the result is Error: locator.isVisible: Test ended. The third one will display an error, that the item is hidden but in reality it is visible since the first assert works.

What exactly is wrong with 2nd and 3rd assertions ?

1

There are 1 best solutions below

7
Infern0 On

there is a bit confusion about your code, let me try explain.

await page.getByText('Thank you for your purchase!', { exact: true }).isVisible();

This is not an assertion, it returns true/false for visability.

await expect (page.getByText('Thank you for your purchase!', { exact: true }).isVisible());

You don't provided expectation condition, since the evaluation of expect returns true/false, you have to provide condition like: toBe()

expect(page.getByText('Thank you for your purchase!', { exact: true })).toBeVisible();

This is actual expect with condition, but you did not provide await.

Here is more readable explanation with corrections:

// get element visibility.
const isVisible: boolean = await page.getByText('Thank you for your purchase!', { exact: true }).isVisible();
console.log(`Is Visible?: ${isVisible}`);

// assert element visibility is true
expect(await page.getByText('Thank you for your purchase!', {exact: true}).isVisible()).toBe(true);

// do polling for expect element to be visible.
await expect(page.getByText('Thank you for your purchase!', { exact: true })).toBeVisible();