testingplaywright

Playwright - No longer running setup action


I have a project which has this setup :

MyProject
 -- tests
    playwright.config.js
    package.json
    -- playwright
       -- setup
          auth.js
       -- specs
          example.spec.js

The setup login into the website. It's required for others tests.

Here is my playwright.config.js

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

export default defineConfig({
  testDir: './playwright/specs',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 1 : undefined,
  reporter: 'html',
  use: {
    trace: 'on-first-retry',
  },

  projects: [
    {
      name: 'setup',
      testMatch: "./playwright/setup/auth.js"
    },
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        storageState: './playwright/.auth/user.json'
      },
      dependencies: ['setup'],
    },
    {
      name: 'firefox',
      use: {
        ...devices['Firefox'],
        storageState: './playwright/.auth/user.json'
      },
      dependencies: ['setup'],
    }
  ]
});

After the first run, it was working fine, the file .auth/user.json was generated and tests were well logged. But then, I removed the file to make it re-login, but it never run the setup again. Each time, it directly try to run tests, which leads to failure:

Error: Error reading storage state from ./playwright/.auth/user.json:
ENOENT: no such file or directory, open 'C:\Dir\To\MyProject\tests\playwright\.auth\user.json'

How can I force to run the "setup" step ?

I'm running npx playwright test from folder "tests"


Solution

  • I skipped the problem by using test.beforeEach() like this:

    test.beforeEach(async ({ page }) => {
        // now auth to website
    });
    

    But, this wasn't run for all tests. Also, I got problems with so much different connection. So I changed to:

    async function loginWithUser(page, user) {
        var cookie = cookiesPerUser[user];
    
        if(cookie) {
            page.context().addCookies([ cookie ]);
            await page.goto(data["URL"] + 'login'); // check if logged
            if(await page.getByRole('link', { name: 'Tableau de bord' }).isVisible()) {
                console.log("Connexion re-used for user " + user);
                return;
            }
            // else go make a new connection
        }
    
        // now login the same as before
    
        var cookies = await page.context().cookies();
        for(var c of cookies) {
            if(c.name == "PHPSESSID") // the token for session
                cookiesPerUser[user] = c
        }
    }
    

    And then, every test run await loginWithUser(page, 'admin') at first line.