afterEach for multiple spec files

887 Views Asked by At

I'm looking for a way to run some common code across tests in multiple spec files in Playwright typescript. My particular case is wanting to upload test results based on testInfo. I'm aware that fixtures can be used for this, but this is not ideal. With fixtures, I need to specify the fixture for every test, and in my case I don't need to reference the fixture within my tests. This makes it easy to not include the fixture on new tests, and accidentally remove it with lint clean up on existing tests.

I have seen that importing files that include beforeAll or afterAll will run that code as expected. But doing the same with beforeEach or afterEach only runs that code once, instead of once for each test.

Is there a way to get functionality like beforeEach or afterEach for multiple spec files without having to add superfluous code to each test?

1

There are 1 best solutions below

0
On

The best way I've found to do this is to have common file that you import into each test file and call. This works well for beforeEach and afterEach. However, beforeAll and afterAll applies to each spec file. So each will be called once for each spec file, and not for the whole group. If you want those to run once for the whole set of specs a better option is using globalSetup and globalTeardown.

Common file:

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

export function setupGlobalHooks() {
  test.beforeAll(() => {
    // Before all tests
  });

  test.beforeEach(() => {
    // Before each test
  });

  test.afterAll(() => {
    // After all tests
  });

  test.afterEach(() => {
    // After each test
  });
}

A spec file:

import { test } from "@playwright/test";
import { setupGlobalHooks } from "./global";

setupGlobalHooks();
...

Alternatively, you could also have a set of shared functions that you call in each specs beforeEach and afterEach. But I like the above a little better as it's very obvious if you're missing the common hooks.

There is a feature request written. So hopefully there will be a better solution. Note, the solution in the second post appears to work, but fails if the number of workers is 1. Both the *All and *Each hooks will only run for the first spec run.