Dramatist: Unable to import session storage data from a JSON file into the browser environment

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"],
    },
  ],
});

Answer №1

If you're working on a 'chromium' project, don't forget to include the storageState option in the configuration file's use section:

/* Setting up projects for popular browsers */
projects: [
// Project setup
 {
   name: "setup",
   testMatch: /.*\.setup\.ts/,
   testDir: "setup",
 },
 {
   name: "chromium",
   use: {
     ...devices["Desktop Chrome"],
     storageState: `playwright/.auth/session.json`,
   },
   dependencies: ["setup"],
 },
],

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the URL string without any parameters in Angular 2

I am in the process of developing a web application using Angular2 (v. 2.1.1) for the frontend. Is there a way to extract the base URL, without any parameters, as a string? If my current URL is foo/bar/1/2/3, I am looking for a method to retrieve just fo ...

Sending a Typed useState Hook to a child component results in it being interpreted as undefined, even if the defaultState is not

This code snippet showcases my attempt at creating a form with the functionality to generate multiple entries of the same form upon a button click. The ultimate goal is to store the input data in an array of objects, where each object corresponds to one co ...

Unable to retrieve the JSON data obtained with node-fetch

I'm having trouble accessing elements inside a json object fetched from a url using node-fetch. Despite being able to log the json object on the console, I encountered errors like TypeError: data.forEach is not a function when attempting to call a met ...

:host background color may be missing, but the font size has been boosted?

Check out this demo where the CSS is applied to the :host element or <hello>. The font size increases but the background color remains unchanged. What do you think? styles: [` :host { font-size: 2rem; background-color: yellow; }`] }) ...

Toggle visibility of an Angular 4 component based on the current route

Hello there, I'm facing an issue and not sure if it's possible to resolve. Essentially, I am looking to display a component only when the route matches a certain condition, and hide another component when the route matches a different condition. ...

Is there a way to automate downloading a file in Angular using the browser's built-in download feature?

When I make a request to my webservice to download a zip file, the file content is downloaded secretly and suddenly appears in the download task bar as already fully downloaded (100%). I am using the following method in Angular: const endpoint = "http:// ...

Leverage TypeScript exclusively for type-checking JavaScript code with JSDoc annotations

I am looking to incorporate types in an existing JS project specifically for IDE syntax highlighting, without adding to the library @types/. For example, I have a file named 'TestComponent.js': export const TestComponent = (props) => { re ...

Exploring Angular 4: Embracing the Power of Observables

I am currently working on a project that involves loading and selecting clients (not users, but more like customers). However, I have encountered an issue where I am unable to subscribe to the Observables being loaded in my component. Despite trying vario ...

Confirm that the attributes of a JSON object align with an Enum

Having a Lambda function that receives a JSON object from the Frontend over HTTPS, I need to perform validation on this object The expected structure of the body should be as follows (Notifications): interface Notifications { type: NotificationType; f ...

What causes React component state initialization to return a `never` type when set to null?

Initializing a component's state to null outside of the constructor results in the state having the type never in the render function. However, when the state is initialized within the constructor, the correct type is maintained. Despite many StackO ...

Invoking Component Function via Service

I am in the process of developing a file upload feature for my application. Once the files are successfully uploaded, I want to clear the list of uploaded files. To achieve this, I have created the following function in the file uploader component: clea ...

Determining the best application of guards vs middlewares in NestJs

In my pursuit to develop a NestJs application, I aim to implement a middleware that validates the token in the request object and an authentication guard that verifies the user within the token payload. Separating these components allows for a more organi ...

What is causing my click event, which I included in a table row, to not function properly?

I'm having trouble with this code I wrote. When I click on a row in the table (tr tag), nothing happens and I can't figure out why... readDetails(){ this.router.navigate(['/dettaglio-contributivo']); console.log("It should work ...

What is the best approach for utilizing Inheritance in Models within Angular2 with TypeScript?

Hey there, I am currently dealing with a Model Class Question and a ModelClass TrueFalseQuestion. Here are the fields: question.model.ts export class Question { answerId: number; questionTitle: string; questionDescription: string; } truefals ...

What happens when i18next's fallbackLng takes precedence over changeLanguage?

I am currently developing a Node.js app with support for multi-language functionality based on the URL query string. I have implemented the i18next module in my project. Below is a snippet from my main index.ts file: ... import i18next from 'i18next& ...

Optimal strategy for initializing class members

When declaring a class with a member like: import {Subject} from "rxjs"; export class MyClass { protected subject: Subject<string>; } what is the preferred practice in TypeScript for initializing the subject member? Is it better to do it in the ...

What is the method for filtering out specific fields in a template string?

I am currently working on defining constraints for the method field type event = { [k: `on${string}`]:(e:string)=>void } However, I need the event argument to be a number for fields that do not begin with 'on' type event = { [k: ` ...

What is the best way to remove a parent app.js element from a child component?

When I click the delete button, my intention is to filter an array in the parent app.js component and remove a specific item. However, I keep encountering a Typescript error stating Cannot assign to read only property 'message' of object 'Sy ...

Utilizing TypeScript for enhanced Chrome notifications

I am currently developing a Chrome app using TypeScript (Angular2) and I want to implement push notifications. Here is the code snippet for my notification service: import {Injectable} from 'angular2/core'; @Injectable() export class Notificati ...

Illustrative demonstration of Vue with TypeScript

I am currently working on developing a HelloWorld application using Vue.js and TypeScript. index.html <script data-main="app.js" src="node_modules/requirejs/require.js"></script> <div id="app">{{text}}</div> app.ts import Vue f ...