0

I'm trying to make tests for a webapplication with Playwright test in JavaScript, but I would like to make them modular, to avoid repeating code. Let's say two tests need to fill a form. Instead of writing code to fill the form in both tests, is it possible to include a file in these two tests that contains filling the form?

import { test, expect } from '@playwright/test';

test.describe("", () => {
    //create a new page
  test.beforeAll( async ({ browser }) => {
    let page = await browser.newPage();
   
    await page.goto('https://www.example.com/');
  })

test('Do stuff', async () => {
import{test} from 'login.spec.mjs';
import{test} from 'fillform.spec.mjs';
})

login.spec.mjs

test('Login', async () => {
       
  // Click input[name="username"]
   await page.click('input[name="username"]');
//...
})

How do we call these functions, which are all named "test()"? Is this a good way to approach testing?

Dries
  • 11
  • 2
  • 1
    Use page object model pattern: https://playwright.dev/docs/pom And also fixtures: https://playwright.dev/docs/test-fixtures – senaid Dec 10 '21 at 15:23

1 Answers1

0

You can create a function called login() that does takes in parameters that will fill out the form.

For instance, you can do the following:

import { test, expect } from '@playwright/test';

function loginForm(page, input1, input2) {
     await page.goto('URL NAME HERE');
     await page.fill('#inputID1', input1);
     await page.fill('#inputID2', input2);
     await page.click('#loginButton');
}

test('Test Login for User 1', async ({page}) => {
     loginForm(page, 'username1', 'password1');
     // Do more stuff here

}

test('Test Login for User 2', async ({page}) => {
     await loginForm(page, 'username2', 'password2');
     // Do more stuff here

}

test('Test Login for User 3', async ({page}) => {
     await loginForm(page, 'username3', 'password3');
     // Do more stuff here

}