Playwright baseUrl in playwright.config.ts does not work in tests

1.4k Views Asked by At

I'm having an issue setting the baseURL for my project. By all tutorials that I watched and tried to replicate, setting the baseURL in the playwright.config.ts should do the trick. However, when I try to use inside the test or a class, the URL comes empty.

Basically what I did:

playwright.config.ts

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

const config: PlaywrightTestConfig = {
  baseURL: 'https://example.com',
};

export default config;

mytest.spec.ts

test('Example test', async ({ page, config }) => {
 await page.goto('/');
}

Does the test need any type of import for it to work? Isn't playwright.config.ts global?

2

There are 2 best solutions below

1
Luc Gagan On

I believe that your playwright.config.ts should be:

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

export default defineConfig({
  use: {
    baseURL: 'https://example.com',
  },
});

Now anywhere in the test if you use non-absolute URL, it will assume https://example.com as the base of the URL.

0
Enrique Lopez On

I had the same issue before, in my case the Url was not properly set because I was using an env var that was not propagating correctly.

I was dong something like

use: {
  baseURL: process.env.URL <- I had a problem with my env variable
},

Just in case, I would suggest to hardcode the value directly in the playwright.config.ts only to debug and confirm that the value is there.

Also one of the best ways to finally fix any problem with the baseURL is to create a second node project, but this time using the official playwright template, you can install the playwright template with this command:

npm init playwright@latest

And then you can compare your wrong playwright.config.ts against the template.


Also remember that there are two places in the config file where you can set baseURL

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

export default defineConfig({
  use: {
    baseURL: 'https://example.com', <-- Global for all test files
  },
  projects: [
  {
    name: 'chromium',
    use: {
      ...devices['Desktop Chrome'],
      baseURL: 'https://anotherpage.com', <-- Overrides global baseURL
    }
  }
  ]
});

Hope it helps!