1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2025-05-02

はじめに

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'],
    },
  ],
});
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?