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.

How to conditionally use afterEach in your Playwright Tests

There are certain scenarios that you may run into where you want to use an afterEach in a test to clean up data, but not every scenario needs this data cleaned up. My specific example was a test where I was testing a POST endpoint. We have both positive and negative tests. When I successfully create with a POST I want to delete what I just created in an afterEach, but where I ran a negative test where I POST but expect a new item isn't created, I shouldn't need to run the afterEach to clean up that data, the afterEach would actually fail passing the id I want to delete, because it doesn't exist.

The solution was to make afterEach 'triggerable'. See the below code example, where we create a new variable triggerAfterEach and set to true in order to trigger an afterEach. If I don't assign triggerAfterEach in a test the afterEach code wouldn't be executed.


test.describe("Test Group", async () => {
  let triggerAfterEach: boolean;

  test.afterEach(async () => {
    if (triggerAfterEach) {
      //execute after code here
    }
  });

  test("Test Scenario with afterEach", async () => {
    triggerAfterEach = true;

  });

  test("Test Scenario without afterEach", async () => {
    triggerAfterEach = false;

  });
});

Credit Sergei for the solution!