Sponsored Link
Looking for a unified way to  viewmonitor, and  debug Playwright Test Automation runs?
Try the Playwright Dashboard by today. Use the coupon code PWSOL10 for a 12 month 10% discount.

Is it possible to get the current Playwright test name while the test is running?

This post is specifically for Playwright Typescript using the Playwright Test Runner.

The Playwright team has included a TestInfo class, that includes this information, and a whole lot more!

test.describe("/admin", () => {
  test("login with valid user", async ({ page }, testInfo) => {
    await page.goto("https://automationintesting.online/#/admin");

    console.log(testInfo.title);
    console.log(testInfo.titlePath);
  });
});

The output is listed below, one is a string while the other is an array of strings.

login with valid user
[
  'tests/login.spec.ts',
  '/admin',
  'login with valid user'
]
output

Some other interesting methods that can be called on the TestInfo class include:

  • testInfo.config - This will return an object of the config in the Playwright configuration file playwright.config.ts. This can be useful for doing conditional checks or skips in your tests or to be able to use this information within a specific test.
  • testInfo.error - This will return the first error
  • testInfo.errors - This will return an array of errors during the test execution
  • testInfo.retry - This specifies the retry number that is being attempted. If you have retries enabled for your suite or a specific spec this would allow you to perform actions conditionally depending on which retry it is. The first run starts at 0 while retry 1 would return 1 and so forth. I could see this being really useful for cleaning up data or attempting to reset the state of a test on a retry.
import { test, expect } from '@playwright/test';

test.beforeEach(async ({}, testInfo) => {
  // You can access testInfo.retry in any hook or fixture.
  if (testInfo.retry > 0)
    console.log(`Retrying!`);
});

test('my test', async ({ page }, testInfo) => {
  // Here we clear some server-side state when retrying.
  if (testInfo.retry)
    await cleanSomeCachesOnTheServer();
  // ...
});
  • testInfo.status - This can be useful to include in an after each block to make conditional checks against testInfo.expectedStatus.
import { test, expect } from '@playwright/test';

test.afterEach(async ({}, testInfo) => {
  if (testInfo.status !== testInfo.expectedStatus)
    console.log(`${testInfo.title} did not run as expected!`);
});

The official docs for this can be found at the TestInfo class.

The title and other information can also be access through the Reporter class, but we'll save that for another post.


Thanks for reading! If you found this helpful, reach out and let me know on LinkedIn or consider buying me a cup of coffee. If you want more content delivered to you in your inbox subscribe below.