🎭

Playwrightでログイン状態を保持する

に公開

はじめに

Webアプリケーションのテストで「あらかじめログインした状態からテストを始めたい」というのはよくあるニーズです。Playwrightでは、Authenticationにあるように、ログイン後の browser state を保存して、使い回すのが基本的な実装方法です。ここではサンプルコードを紹介します。

ログイン状態の保持

セッションの保存

tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

const sessionFile = '.auth/user.json';

setup('ログイン', async ({ page }) => {
  // Perform authentication steps. Replace these actions with your own.
  await page.goto('/login');
  await page.getByLabel('アカウント名').fill('username');
  await page.getByLabel('パスワード').fill('password');
  await page.getByRole('button', { name: 'ログイン' }).click();
  await page.waitForURL('/home');
  await expect(page.getByRole('heading', { name: 'Welcome to HOME' })).toBeVisible();

  // End of authentication steps.

  await page.context().storageState({ path: sessionFile });
});

テストケースで使うための設定

ポイントは、以下の2点です。

  1. chromium プロジェクトの dependenciessetup を指定することで、テストケース実行前に setup が実行されるようにする。
  2. chromium プロジェクトの usestorageState を指定することで、テストケース実行時に setup で保存したセッションを読み込むようにする。
playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    // Setup project
    { name: 'setup', testMatch: /.*\.setup\.ts/ },

    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        // Use prepared auth state.
        storageState: '.auth/user.json',
      },
      dependencies: ['setup'],
    },
  ],
});

GitHubで編集を提案

Discussion