DEV Community

Kayode
Kayode

Posted on • Originally published at blog.zt4ff.dev on

Playwright Tutorial for Beginners 9 - Assertions

Playwright Assertions

Playwright make use of expect library (provided by Jest) for assertions. The library provides different types of matchers like toEqual, toContain, toMatch, toMatchSnapshots and many more.

To make use of the library, import it into your test script.

const { expect } = require('@playwright/test')

Enter fullscreen mode Exit fullscreen mode

You can extend with async matchers that will wait until the specified assertion condition is met.

expect(value).toEqual(anotherValue);

await expect(value).toBeTruthy();

Enter fullscreen mode Exit fullscreen mode

Common patterns

// assert text content
expect(await page.locator('.welcomeMsg').textContent()).toEqual('Welcome pal');

// assert inner text
expect(await page.locator('.goodbyeMsg').innerText()).toBe('Goodbye pal');

// assert inner html
expect(await page.locator('.button-container').innerText()).toEqual(
    '<button>Submit</button>'
  );

// assert attribute
expect(await page.locator('css=#name-input')).toHaveAttribute('type', 'text');

// assert url
expect(await page.url()).toMatch(/\/users\/test/);

// and many more!

Enter fullscreen mode Exit fullscreen mode

Custom assertions

To have custom assertions, you can extend the expect provided by Jest. For instance, we will create a custom matcher called toBeBetween10And100:

const { expect, default: test } = require('@playwright/test');

expect.extend({
  toBeBetween10And100(num) {
    const pass = num > 10 && num < 100;

    if (pass) {
      return {
        message: () => `expected ${num} to be not within 10 and 100`,
        pass: true
      };
    }
    return {
      message: () => `expected ${num} to be within 10 and 100`,
      pass: false
    };
  }
});

test('simple test', async () => {
    // pass
  expect(25).toBeBetween10And100();
});

Enter fullscreen mode Exit fullscreen mode

There are a bunch of matchers you can use with Playwright depending on what your test suites are.

Top comments (0)