CenterADiv
CenterADiv

Reputation: 81

Playwright use dynamic port for devserver

Problem: When running playwright test in azure pipeline, The port 3000 is already in use sometimes(maybe other pipeline runs on the same azure agent)

I think instead of using another port like 3001 it would be better to assign the port automatically, meaning a free port will be choosen.

I looked at this issue but i dont want to modify my webpack config. Is there a way to configure this behaviour in the playwright config?

Here are the configs i refer to:

I have this entry in playwright.config.ts

 webServer: {
     command: 'npm run start',
     timeout: 120 * 1000,
     port: 3000
  },

And this webpack dev server configuration:

 devServer: {
     port: 3000,
     compress: true,
     open: true,
     watchFiles: 'src',
     historyApiFallback: true,
     client: {
        overlay: {
           errors: true,
           warnings: true,
            runtimeErrors: false,
        },
     },
 },

Upvotes: 0

Views: 1016

Answers (1)

CenterADiv
CenterADiv

Reputation: 81

Instead of manually setting a port, I implemented a workaround to dynamically find an available port and use it for Playwright tests.

Solution

In playwright.config.ts, I check if BASE_URL is already set. If not, I assign a random available port (between 10,000 and 30,000) when running in CI. For local development, I use a fixed port (8088).

playwright.config.ts

// Assign a dynamic port if not already set
if (!process.env.BASE_URL) {
  const portRange = { min: 10000, max: 30000 };
  const port = process.env.CI
    ? Math.floor(Math.random() * (portRange.max - portRange.min) + portRange.min)
    : 8088;

  process.env.BASE_URL = `http://localhost:${port}`;
  process.env.PORT = String(port);
}

Upvotes: 0

Related Questions