storageState 保存和恢复登录状态

Playwright 提供 storageState 文件(JSON格式)来保存浏览器的登录状态。

1、生成登录状态文件(登录一次)

新建一个脚本 login.js:

const { chromium } = require(‘playwright’);

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();

await page.goto(‘http://localhost:8000/login’);
await page.fill(‘input[name=”username”]’, ‘testuser’);
await page.fill(‘input[name=”password”]’, ‘testpassword’);
await page.click(‘button[type=”submit”]’);
await page.waitForURL(‘**/dashboard’);

// 保存登录状态到文件
await page.context().storageState({ path: ‘storageState.json’ });

await browser.close();
})();

执行:

node login.js

2、在测试中复用登录状态

playwright.config.js 配置:

module.exports = {
use: {
storageState: ‘storageState.json’,
},
};

测试脚本就可以直接跳过登录:

const { test, expect } = require(‘@playwright/test’);

test(‘访问主页,使用已登录状态’, async ({ page }) => {
await page.goto(‘http://localhost:8000/dashboard’);
await expect(page.locator(‘text=欢迎,testuser’)).toBeVisible();
});

作者 admin

百度广告效果展示