My task is to test an application built with React and NestJS. The session token can be found in the sessionStorage of my browser.
To guide me through this process, I referred to the relevant part of the Playwright documentation: https://playwright.dev/docs/auth#session-storage
I successfully saved the JSON file as required, but I am facing difficulties loading it during the tests. I am unsure about where to place the code snippet provided in the documentation:
// Set session storage in a new context
const sessionStorage = JSON.parse(fs.readFileSync('playwright/.auth/session.json', 'utf-8'));
await context.addInitScript(storage => {
if (window.location.hostname === 'example.com') {
for (const [key, value] of Object.entries(storage)) {
window.sessionStorage.setItem(key, value);
}
}
}, sessionStorage);
I attempted to use it in the beforeEach function without success. Can you please guide me on the correct way to utilize this code?
I also tried using the storageSate method but it only saves cookies, not the sessionStorage data.
The content of auth.setup.ts:
import { test as setup } from "@playwright/test";
import path from "path";
import fs from "fs";
require("dotenv").config();
const authFile = path.join(__dirname, "auth.json");
setup("authenticate", async ({ page }) => {
// Authentication steps here. Modify these actions according to your requirements.
await page.goto(process.env.ROOT_URL + "/login");
await page.locator("input[placeholder=Email]").fill(process.env.LOGIN);
await page
.locator("input[placeholder='Password']")
.fill(process.env.PASSWORD);
await page.click("button[type=button]");
await page.waitForURL(process.env.ROOT_URL + "/selectCompanies");
const sessionStorage = await page.evaluate(() =>
JSON.stringify(sessionStorage)
);
fs.writeFileSync(authFile, JSON.stringify(sessionStorage), "utf-8");
});
Configurations:
export default defineConfig({
testDir: "./tests",
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: "html",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
screenshot: "only-on-failure",
headless: false,
},
/* Configure projects for major browsers */
projects: [
// Setup project
{
name: "setup",
testMatch: /.*\.setup\.ts/,
testDir: "setup",
},
{
name: "chromium",
use: {
...devices["Desktop Chrome"],
},
dependencies: ["setup"],
},
],
});