When navigating the website with Playwright, facing the issue of not being able to utilize storageState

Trying to utilize playwright setup and pre-authenticated users for running tests, encountered an issue where the storage file is set but not being utilized by playwright. Below are the codes used:

auth.setup.ts

import { test as setup, expect } from "@playwright/test";
import * as path from "path";
import fs from "fs";
import { loginAsAdmin } from "./utils";
const authFile = path.join(__dirname, "playwright", ".auth", "user.json");
console.log(`Auth file setup: ${authFile}`);

setup("Authenticate/Login", async ({ page }) => {
  await loginAsAdmin(page); // login logic
  await page.context().storageState({ path: authFile });
  console.log(`Storage state saved to: ${authFile}`);
});

playwright.config.ts

import { defineConfig, devices } from "@playwright/test";
import dotenv from "dotenv";
import * as path from "path";

// check if the current directry is

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

/**
 * Read environment variables from file.
 * https://github.com/motdotla/dotenv
 */
require("dotenv").config();
dotenv.config({
  path: __dirname + "\\.env",
});

/**
 * See https://playwright.dev/docs/test-configuration.
 */
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: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    baseURL: "http://127.0.0.1:3000",

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: "on-first-retry",
  },

  /* Configure projects for major browsers */
  projects: [
    { name: "setup", testMatch: /.*\.setup\.ts/ },
    {
      name: "chromium",
      use: {
        ...devices["Desktop Chrome"],
        storageState: authFile,
      },
      dependencies: ["setup"],
    },   
  ],

  /* Run your local dev server before starting the tests */
  webServer: {
    command: "pnpm run dev",
    url: "http://127.0.0.1:3000",
    reuseExistingServer: !process.env.CI,
  },
});

my test example:

await page.goto("http://localhost:3000/en/profile");

Upon visiting the profile page, it displays in an unauthenticated state despite the existence of the authfile and similar paths for setup and config files.

Answer №1

The problem arose due to a discrepancy in the code used in auth.setup.js compared to what was utilized by me. In the former, the snippet `page.goto("/login")` was employed, while I opted for `

await page.goto("http://localhost:3000/en/profile");
The result of this disparity was that the auth.setup.js was redirecting to `http://127.0.0.1:3000` instead of the intended localhost, causing the browser to flag it as a separate website.

To resolve this issue, one could either standardize all links to `localhost`, or refrain from specifying the domain when using the `page.goto()` function.

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

Passing data from a parent component to a child component in Next.JS 13

Struggling to make NextJS work seamlessly with props and passing them between components? It feels like a React-specific challenge, but after scouring Google for answers, the results are scarce. My goal is simple: send a useState value along with its sette ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...

Troubleshooting undefined object values in JavaScript

click here for the imageI am currently utilizing the quotes API in order to retrieve and display quotes. While I am able to print the entire object containing all information about the quote, I am encountering an issue where I cannot access the specific va ...

In the production environment, Auth.js v5 Google login redirects to https://localhost once the login is successful

This function handles the Google login process. "use server"; import { AuthError } from "next-auth"; import { signIn } from "@/auth"; export const googleLogin = async () => { try { await signIn("google", ...

Develop a RESTful API in Node.js that allows for the sending of audio files along with JSON

My current project involves a REST API that I've built using node and express. I'm now facing a challenge where I need to send both JSON Data and an Audio File in a single http request. The audio file needs to be playable on the client side. JSO ...

Unable to retrieve the JSON data located within the object's property

I am currently working on a LitElement project and have successfully added JSON data to the category.items property using the following code: fetchItems(category) { if (!category || category.items) { return; } this.getResource({ ...

How to style a date and time object using angularjs

What is the best way to convert a PHP datetime object to the format "May-27-1990"? ...

Utilizing jQuery to generate dynamic nested divs within the ul li tags

I am looking to dynamically generate nested divs within a ul li. The goal is to create the following structure programmatically: <ul> <li> <div class="videoThumbnail"> <img src="./img6.jpg" /> &l ...

When using iOS, the video compressing process stops automatically if the screen is no longer active while the file input

I am working on a web application that includes a file upload feature for large videos, typically 30 minutes or longer in duration. When a user on an iOS device selects a video to upload, the operating system will automatically compress it before triggerin ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

retrieve HTML content from XML document using the correct user input

I am looking to create a section of an HTML page that can only be accessed through a specific code. The page is coded using pure HTML, CSS, and JavaScript. Here is the proposed logic: User inputs a string into a form Upon clicking the submit button, an ...

Manifestation for JSON Firebug extension

In the process of developing a firebug extension, I encountered an issue with displaying JSON in the panel. Despite using a textarea to display the panel, the extension consistently crashes. Here is what I attempted: var template = domplate( { ...

Is it possible to duplicate this jQuery/Javascript feature using PHP?

I have the code to fetch tweets in JavaScript, but I need it converted to PHP. Can anyone provide any guidance on how to achieve this? $(document).ready( function() { var url = "http://twitter.com/status/user_timeline/joebloggs.json?count=1 ...

Struggling with a TypeORM issue while attempting to generate a migration via the Command Line

Having some trouble using the TypeORM CLI to generate a migration. I followed the instructions, but when I run yarn run typeorm migration:generate, an error pops up: $ typeorm-ts-node-commonjs migration:generate /usr/bin/env: ‘node --require ts-node/regi ...

Monitoring $scope modifications within a directive: A simple guide

I am currently working with a directive that looks like this: app.directive('selectedForm', function(MainService) { return { scope: { formName: '=currentForm' }, restrict: 'E', ...

Troubleshooting Vue 3 Computed Property Not Updating

I'm currently facing a challenge while developing a login form using Vue 3. I am having difficulty in getting the state to update 'realtime' or computed. When attempting to login a user from the template, the code looks like this: <button ...

An automated feature that smoothly transitions a large image onto the screen

I came across a plugin, possibly a slideshow plugin, that smoothly slides a large image along the y-axis. It's hard to explain, but imagine the visible image is only 600px by 300px, while the actual image is 600px by 600px. This plugin would scroll t ...

Obtain the YouTube video identifier from a YouTube embedded link

Is there a way to extract just the YouTube ID from a given URL? https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0 $(".youtube").click(function () { console.log(this.href.replace(new RegExp("em ...

Using either Javascript or JQuery to update every cell in a particular column of a table

I need to use a button to add "OK" in the Status column of table tblItem, which is initially empty. How can I achieve this using JavaScript or JQuery? The table has an id of tblItem Id Item Price Status 1 A 15 2 B 20 3 C ...

Concealing a feature across all pages of the website

I have implemented alert boxes that appear on all pages of the website. https://i.sstatic.net/hWShr.gif Users can individually close each alert box: $(document).ready(function() { $("#close-alert-box-news").click(function() { $("#alert-box-news" ...