Rayrun

How do I create reusable code in Playwright's Test runner using TypeScript's class inheritance?

Answer

To extend your test object in Playwright's Test runner using TypeScript's class inheritance, create a new class that extends Playwright's Test interface and add any additional properties or methods needed. This allows you to create reusable code and reduce duplication in tests.

For example, let's create a new class called LoginTest that extends Playwright's Test interface and adds a "login" method:

import { PlaywrightTestConfig, TestInfo, PlaywrightTest } from '@playwright/test';

class LoginTest extends PlaywrightTest {
  async login(username: string, password: string) {
    const page = await this.page;
    await page.goto('https://ray.run/login');
    await page.fill('#username', username);
    await page.fill('#password', password);
    await Promise.all([
      page.waitForNavigation(),
      page.click('#submit'),
    ]);
  }
}

const config: PlaywrightTestConfig = {
  // ...
};

export default config.use({test: LoginTest});

In this example, we define a new method called "login" that takes two parameters - username and password. Inside the method, we navigate to the login page, fill in the username and password fields, click on the submit button, and wait for navigation.

To use this extended test object in your tests, import it instead of importing from '@playwright/test':

import { expect } from '@playwright/test';
import LoginTest from './login-test';

test('user can log in', async ({ login }) => {
  await login('myusername', 'mypassword');
  const url = await page.url();
  expect(url).toContain('/dashboard');
});

Here, we import the LoginTest class and use it in our test by passing it as a parameter named "login". We can then call the "login" method with the appropriate parameters and perform any additional assertions needed.

By extending Playwright's Test interface using TypeScript's class inheritance, you can create reusable code and make your tests more maintainable.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].