skip to Main Content

Each test uses await expect(page).toHaveScreenshot();. I wouldn’t want to do repetitions in every test.

test.afterEach(async ({ page }) => {
  await expect(page).toHaveScreenshot({mask: [] as Locator[] || null});
});

There is a problem. Some tests have dynamic elements that I need to hide. How do I provide an argument/value for { mask } to handle the first case in some tests?

I tried to give the { mask } a value but to no avail:

test('should open sender`s grid view', async ({ page }) => {
  // some code 
  {mask: value }
});

2

Answers


  1. One possible approach is to use describe blocks that group the different maskings:

    import {test} from "@playwright/test"; // ^1.30.0
    
    test.describe("with empty mask", () => {
      test.afterEach(async ({page}) => {
        await expect(page).toHaveScreenshot({mask: []});
      });
    
      test("foo 1", async ({page}) => {
        // ...
      });
    
      test("foo 2", async ({page}) => {
        // ...
      });
    });
    
    test.describe("with p masked", () => {
      test.afterEach(async ({page}) => {
        await expect(page).toHaveScreenshot({
          mask: [page.locator("p")]
        });
      });
    
      test("bar 1", async ({page}) => {
        // ...
      });
    
      test("bar 2", async ({page}) => {
        // ...
      });
    });
    

    If you don’t want the describe blocks, there’s the more naive pattern of setting a shared variable among tests:

    import {test} from "@playwright/test";
    
    let mask = [];
    
    test.afterEach(async ({page}) => {
      await expect(page).toHaveScreenshot({mask});
      mask = [];
    });
    
    test("foo 1", async ({page}) => {
      // ...
      mask = [page.locator("p"), page.locator("h1")];
    });
    
    test("foo 2", async ({page}) => {
      // ...
    });
    
    test("foo 3", async ({page}) => {
      // ...
      mask = [page.locator("p")];
    });
    
    test("foo 3", async ({page}) => {
      // ...
    });
    

    The mask = []; line ensures that the empty mask is the default value if a test hasn’t overridden it.

    Note that [] || null will never evaluate to null, even if the array is empty. If you want to provide null as the default value, replace all occurrences of let mask = [] and mask = [] with mask = null.

    Login or Signup to reply.
  2. Dynamic elements can be handled using Regex to accommodate many possible scenarios:

    //Locator definition with regex
    const userInfo = page.locator('.user_Info');
    const maskedElements = userInfo
        .filter({ hasText: new RegExp(`^Password Info$`) })
    

    //some steps

    // Assertion with screeenshots with masking

    await expect(page).toHaveScreenshot({mask: [maskedElements]});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search