You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright删除auth文件后未重跑setup,如何强制执行该步骤?

强制Playwright重新执行Setup步骤的解决方法

问题场景

项目结构如下:

MyProject
 -- tests
    playwright.config.js
    package.json
    -- playwright
       -- setup
          auth.js
       -- specs
          example.spec.js

其中setup/auth.js是登录网站的前置步骤,首次运行npx playwright test时正常生成./playwright/.auth/user.json,测试也能正常登录。但删除该文件后,再次执行命令时,setup步骤不再运行,直接抛出错误:

Error: Error reading storage state from ./playwright/.auth/user.json:
ENOENT: no such file or directory, open 'C:\Dir\To\MyProject\tests\playwright.auth\user.json'

解决方法

1. 直接指定运行setup项目

在命令行先强制执行setup项目,再运行常规测试:

npx playwright test --project=setup && npx playwright test

这样会重新执行登录逻辑生成新的user.json,之后再正常执行测试用例。

2. 删除Playwright缓存目录

Playwright会缓存依赖项目的执行状态,删除缓存后会重新触发setup执行。缓存目录默认在tests/.playwright-cache(与playwright.config.js同目录),执行对应系统的删除命令后再跑测试:

# Linux/macOS
rm -rf .playwright-cache

# Windows 命令行
rd /s /q .playwright-cache

之后执行npx playwright test,Playwright会重新检测到setup依赖需要执行。

3. 确保setup强制生成存储文件(推荐)

修改playwright/setup/auth.js,确保每次运行都覆盖生成user.json,避免依赖缓存判断:

import { test } from '@playwright/test';

test('authenticate', async ({ page }) => {
  // 登录逻辑
  await page.goto('/login');
  await page.fill('#username', 'your-username');
  await page.fill('#password', 'your-password');
  await page.click('#submit');
  // 强制保存storage状态,覆盖原有文件
  await page.context().storageState({ path: './playwright/.auth/user.json' });
});

结合方法2清理缓存后,每次执行测试都会重新触发setup步骤生成存储文件。

内容的提问来源于stack exchange,提问作者Elikill58

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:42:22