😽

PlaywrightテストでGoogleの認証をskipする

2024/10/03に公開

PlaywrightでGoogleの認証をskipする

Playwrightで一回自動ログインして、user.jsonファイルを生成する

  • Playwrightで一回自動ログイン
  • 生成されるuser.jsonファイルにCookieなど認証後の情報が入っている
  • 以下のコードを実行してできる
import { test as setup } from "@playwright/test";
import path from "path";

const authFile = path.join(__dirname, "../playwright/.auth/user.json");

setup("authenticate2", async ({ page }) => {
  setup.setTimeout(60000);
  // Perform authentication steps. Replace these actions with your own.
  await page.goto("http://localhost:3000");
  await page.locator("#identifierId").fill(process.env.GOOGLE_ACCOUNT ?? "");
  await page.locator("//button").getByText("Next").click();

  const url = page.url();
  console.log("Before: current url: " + url);
  await page.waitForTimeout(5000);

  const url2 = page.url();
  console.log("After: current url: " + url2);
  (await page.locator("//input").all()).forEach(async (input) => {
    if ((await input.getAttribute("name")) == "Passwd") {
      console.log("password is filled!");
      input.fill(process.env.GOOGLE_ACCOUNT_PASSWORD ?? "");
    }
  });
  await page.locator("//button").getByText("Next").click();

  await page.waitForTimeout(5000);
  const url3 = page.url();
  console.log("After filling in password: current url: " + url3);
  await page.locator("//button").getByText("許可").click();
  await page.waitForTimeout(5000);
  const url4 = page.url();
  console.log("After filling in final confirm: current url: " + url4);

  await page.waitForURL("$Your_target_url");
  await page
    .getByTestId("$your_test_id")
    .waitFor({ state: "visible", timeout: 10000 });

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

playwright.config.tsを設定して、テストの時認証が不要

  • storageState: "playwright/.auth/user.json"の設定
  • テストする前にuser.jsonの認証後の情報を自動的に導入されて、認証がない状態で自分の画面テストを実行できる。
projects: [
    { name: "setup", testMatch: /.*\.setup\.ts/ },
    {
      name: "chromium",
      use: {
        ...devices["Desktop Chrome"],
        storageState: "playwright/.auth/user.json",
      },
      // dependencies: ["setup"],
    },

    {
      name: "firefox",
      use: {
        ...devices["Desktop Firefox"],
        storageState: "playwright/.auth/user.json",
      },
      // dependencies: ["setup"],
    },

    {
      name: "webkit",
      use: {
        ...devices["Desktop Safari"],
        storageState: "playwright/.auth/user.json",
      },
      // dependencies: ["setup"],
    },
}

Discussion