Utiliser storageState() pour l'authentification
Authentification des tests en utilisant les cookies de session sauvegardés de Playwright
Si vos tests nécessitent des sessions authentifiées, vous pouvez utiliser le storageState() de Playwright pour charger les cookies d'authentification précédemment sauvegardés dans le contexte du navigateur. Comme Axe Watcher utilise ses propres fixtures de Playwright, vous devez fusionner la fixture d'authentification avec la fixture d'Axe Watcher en utilisant mergeTests.
Fichier de Fixtures
Créez un fichier fixtures.ts qui lit les cookies à partir d'un fichier storageState.json sauvegardé et les injecte dans le BrowserContext de 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 }Utilisation dans les Tests
Dans vos fichiers de test, appelez authCookie.inject() avant de naviguer vers des pages authentifiées :
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
})Générez storageState.json avant d'exécuter vos tests en utilisant le installation globale de Playwright. Ce fichier contient des cookies d'authentification et ne doit pas être ajouté au contrôle de source.
