How to Run a Specific Spec File During `globalSetup` in Playwright?

I’m trying to run a specific spec file (math.spec.js) during the globalSetup phase in Playwright. The goal is to execute this spec file before any other tests run.

Here’s the structure of my project:

/my-project
|-- tests/
|   |-- e2e/
|       |-- pos/
|           |-- math.spec.js
|-- playwright.config.js
|-- global-setup.js

In global-setup.js, I want to run the math.spec.js file using the Playwright test runner. I’ve tried using Node’s child_process to execute the command, but I’m not sure if this is the best approach or if there is a built-in way in Playwright to handle this.

global-setup.js:

const { execSync } = require('child_process');

module.exports = async () => {
  try {
    // Attempt to run the specific spec file
    execSync('npx playwright test tests/e2e/pos/math.spec.js', { stdio: 'inherit' });
  } catch (error) {
    console.error('Error running math.spec.js in global setup:', error);
    process.exit(1); // Exit with a failure code if the test fails
  }
};

playwright.config.js:

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

export default defineConfig({
  globalSetup: require.resolve('./global-setup.js'),
  // Other configurations...
});

Questions:

  • Is this the correct way to run a specific spec file during globalSetup in Playwright?
  • Are there any best practices or potential issues with this approach?
  • Is there a more Playwright-native way to achieve this?

I’m using Playwright version 1.46.1 and Node.js version 20.15.1.