Usare storageState() per l'autenticazione

This page is not available in the language you requested. You have been redirected to the English version of the page.
Link to this page copied to clipboard

Autenticare i test utilizzando i cookie di sessione salvati di Playwright

Not for use with personal data

Se i tuoi test richiedono sessioni autenticate, puoi utilizzare storageState() di Playwright per caricare i cookie di autenticazione precedentemente salvati nel contesto del browser. Poiché Axe Watcher utilizza i suoi propri fixture di Playwright, devi unire il fixture di autenticazione con il fixture di Axe Watcher utilizzando mergeTests.

File dei Fixture

Crea un file fixtures.ts che legga i cookie da un file storageState.json salvato e li inietti nel BrowserContext di Playwright:

import { readFileSync } from 'fs'
import { test as base, type BrowserContext, mergeTests } from '@playwright/test'
import { playwrightTest } from '@axe-core/watcher/playwright-test'

// Environment variables for Axe Developer Hub
const ACCESSIBILITY_API_KEY = process.env.ACCESSIBILITY_API_KEY
const PROJECT_ID = process.env.PROJECT_ID
const SERVER_URL = process.env.SERVER_URL

// Configure Axe Watcher
const { test: watcherTest, expect } = playwrightTest({
  axe: {
    apiKey: ACCESSIBILITY_API_KEY,
    projectId: PROJECT_ID,
    serverURL: SERVER_URL
  },
  headless: false
})

// Custom fixture: Cookie-based authentication
class AuthCookie {
  #context: BrowserContext

  constructor(context: BrowserContext) {
    this.#context = context
  }

  async inject() {
    await this.#context.addCookies(
      JSON.parse(readFileSync('storageState.json', 'utf-8')).cookies
    )
  }
}

// Define auth cookie fixture
const authCookieFixture = base.extend<{ authCookie: AuthCookie }>({
  authCookie: async ({ context }, use) => {
    const auth = new AuthCookie(context)
    await use(auth)
  }
})

// Merge fixtures
const test = mergeTests(authCookieFixture, watcherTest)

// Export merged test and expect
export { test, expect }

Uso nei Test

Nei tuoi file di test, chiama authCookie.inject() prima di navigare verso pagine che richiedono autenticazione:

import { test, expect } from './fixtures'

test('should display accessible authenticated page', async ({ page, authCookie }) => {
  await authCookie.inject()
  await page.goto('https://example.com/authenticated-page')

  // Accessibility testing happens automatically
})
note

Genera storageState.json prima di eseguire i tuoi test utilizzando configurazione globale di Playwright. Questo file contiene i cookie di autenticazione e non dovrebbe essere inserito nel controllo del codice sorgente.

Vedi Anche