typescript - API request doesn't work in playwright after successful authentication - Stack Overflow

admin2025-05-02  0

This is my setup for login:

import {test as setup} from '@playwright/test'

 const authFile = '.auth/user.json'

 setup('authentication', async ({page}) => {
    await page.goto('/');
    await page.getByRole('textbox', {name: 'Username'}).fill('Admin');
    await page.getByRole('textbox', {name: 'Password'}).fill('Admin');
    await page.locator('#kc-login').filter({hasText: 'Sign In'}).click();
    await page.waitForResponse('');
    
    await page.context().storageState({path: authFile})
 })

and here is my test to rename collection:

import { test, expect, request } from "@playwright/test";

test.beforeEach(async ({ page, request, context }) => {
  await page.goto("/");
  await expect(
    page.getByText("From newest to oldest", {
      exact: true,
    })
  ).toBeVisible();
});

test("Rename collection", async ({ request }) => {
  await request.patch(
    ";,
    {
      data: { name: "Test name", description: "test description" },
    }
  );
});

Config file where authFile is used:

projects: [ 
  { 
    name: 'setup', 
    testMatch: '/globalFiles/auth.setup.ts'
  }, 
  { 
    name: 'chromium for API', 
    use: { 
      ...devices['Desktop Chrome'],  
      storageState: '.auth/user.json', 
    }, 
    dependencies: ['setup'], 
  },
]

My requests just doesn't work after authentication. Playwright just login successfully and then nothing is going on... Just main page is shown. I tried different endpoints (post, get) but always nothing is going on after log in. And playwright always show test as passed. Also in postman everything work correct.

This is my setup for login:

import {test as setup} from '@playwright/test'

 const authFile = '.auth/user.json'

 setup('authentication', async ({page}) => {
    await page.goto('https://justexample.ua/');
    await page.getByRole('textbox', {name: 'Username'}).fill('Admin');
    await page.getByRole('textbox', {name: 'Password'}).fill('Admin');
    await page.locator('#kc-login').filter({hasText: 'Sign In'}).click();
    await page.waitForResponse('https://api.justexample.ua/asset/filter-all-data');
    
    await page.context().storageState({path: authFile})
 })

and here is my test to rename collection:

import { test, expect, request } from "@playwright/test";

test.beforeEach(async ({ page, request, context }) => {
  await page.goto("https://justexample.ua/");
  await expect(
    page.getByText("From newest to oldest", {
      exact: true,
    })
  ).toBeVisible();
});

test("Rename collection", async ({ request }) => {
  await request.patch(
    "https://api.justexample.ua/collection/0856d250-79b7-496d-b0b9-c8163b818816",
    {
      data: { name: "Test name", description: "test description" },
    }
  );
});

Config file where authFile is used:

projects: [ 
  { 
    name: 'setup', 
    testMatch: '/globalFiles/auth.setup.ts'
  }, 
  { 
    name: 'chromium for API', 
    use: { 
      ...devices['Desktop Chrome'],  
      storageState: '.auth/user.json', 
    }, 
    dependencies: ['setup'], 
  },
]

My requests just doesn't work after authentication. Playwright just login successfully and then nothing is going on... Just main page is shown. I tried different endpoints (post, get) but always nothing is going on after log in. And playwright always show test as passed. Also in postman everything work correct.

Share Improve this question edited Jan 2 at 21:52 Bryan Burton 1651 silver badge6 bronze badges asked Jan 2 at 4:16 Igor MerezhkoIgor Merezhko 111 silver badge1 bronze badge 1
  • Can you provide an example page as part of a minimal reproducible example? Otherwise, the code looks fine on an eyeball--there's nothing obviously incorrect here, so it's hard to help without having access to enough of your context to be able to run this and see the error. Keep in mind, we have no idea what a "collection" means in your app--you'll want to define/explain all relevant concepts. Does not work generally doesn't clarify much--better to explain exactly what doesn't work, and what you expected to happen. Thanks. – ggorlen Commented Jan 2 at 4:37
Add a comment  | 

2 Answers 2

Reset to default 2

You have to assign the storage state to the request context. You're assigning it to the page context.

import { test, expect, request } from '@playwright/test';

test("Renaming collection with storageState", async () => { 

    const apiContext = await request.newContext({
        storageState: 'auth.json', 
      });

    const renameCollection = await apiContext.patch(
        "https://api.example.com/collection/0856d250-79b7-496d-b0b9-c8163b818816", 
        { 
            data: { 
                name: "Igor test " + faker.string.numeric(4), 
                description: faker.string.alphanumeric({ length: { min: 5, max: 50 } }) 
            }, 
        }); 
        expect(renameCollection.status()).toBe(200); 
    
    });

You need to load the stored state into APIRequestContext instance - in your case is the request build-in fixture, using it's storageState method.

Here is an example:

test("Rename collection", async ({ request }) => {
    await request.storageState({ path: "auth.json" }); // Put the path of your storageState file

    const response = await request.patch(
      "https://api.justexample.ua/collection/0856d250-79b7-496d-b0b9-c8163b818816",
      {
        data: { name: "Test name", description: "test description" },
      }
    );
    expect(response.ok()).toBeTruthy();
  });
转载请注明原文地址:http://anycun.com/QandA/1746134594a92052.html