storageState() を使用した認証

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

Playwright の保存されたセッション Cookie を使用したテストの認証

Not for use with personal data

テストに認証されたセッションが必要な場合、Playwright の storageState() を使用して、事前に保存された認証 Cookie をブラウザーコンテキストに読み込むことができます。Axe Watcher は独自の Playwright フィクスチャを使用するため、認証フィクスチャを Axe Watcher のフィクスチャと mergeTests する必要があります。

フィクスチャファイル

保存された storageState.json ファイルから Cookie を読み込み、それらを Playwright の BrowserContext に注入する fixtures.ts ファイルを作成します。

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 }

テストでの使用法

テストファイル内で、認証が必要なページに移動する前に authCookie.inject() を呼び出します。

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

テストを実行する前に、Playwright の グローバルセットアップ を使用して storageState.json を生成します。このファイルには認証 Cookie が含まれており、ソース管理にコミットしてはいけません。

参照