return function depending on the variable's value

Viewed 39

I run tests with Playwright and the tests differs if it's mobile or not. When mobile I need to run page.tap() but when desktop I need to run page.click(). I have a working code bellow but how should i prevent DRY code in lots of tests?

Example code


    test("Example test", async ({ page, isMobile }) => {
      async function tapOrClick(selector) {
        if(isMobile){
          await page.tap(selector);
        }
        else {
          await page.click(selector);
        }
      }
      
      await tapOrClick('click on the DOM')
      await tapOrClick('click on the DOM 1')
      await tapOrClick('click on the DOM 2')

    });

Then similar tests will be in another test file.


    test("Example test 2", async ({ page, isMobile }) => {
      async function tapOrClick(selector) {
        if(isMobile){
          await page.tap(selector);
        }
        else {
          await page.click(selector);
        }
      }
      
      await tapOrClick('another click on the DOM')
      await tapOrClick('another click on the DOM 1')
      await tapOrClick('another click on the DOM 2')

    });

1 Answers

Solved it. It became a help class that looks like the following


export class Helper {
  readonly isMobile: boolean;

  constructor(isMobile: boolean) {
    this.isMobile = isMobile
  }

  async clickOrTap(selector: string) {
    if(this.isMobile){
      await this.page.tap(selector);
    }
    else {
      await this.page.click(selector);
    }
  }

}

Use it like this

import { test, expect } from "@playwright/test";
import { Helper } from "../helpers/Helper"

  test("Example test", async ({ page, isMobile }) => {
    const custom = new Helper(isMobile as boolean);
  
    // Click the account button
    await custom.clickOrTap('button[data-element-id=logged-in-sidebar]')

  });


Related