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

如何在Playwright+TypeScript中复用浏览器会话执行测试?

解决Playwright复用登录会话的问题

检查Setup执行状态

  1. 确认登录setup脚本执行成功,生成了playwright/.auth/user.json文件。如果文件不存在:
    • 检查getWelcomeMessage()的实现是否正确,确保expect(await loginPage.getWelcomeMessage()).toBe(true)能通过——只有登录成功后才会执行存储状态的代码。
    • 手动运行setup脚本:npx playwright test login.setup.ts --project=setup,查看日志是否有报错。

修正配置文件细节

  1. 添加baseURL到配置,确保页面跳转路径正确:
    import { PlaywrightTestConfig } from '@playwright/test';
    
    const config: PlaywrightTestConfig = {
      baseURL: 'https://你的应用域名.com', // 替换为实际应用地址
      projects: [
        { name: 'setup', testMatch: /.*\.setup\.ts/ },
        {
          name: 'Chromium',
          use: { 
            browserName: 'chromium',
            storageState: 'playwright/.auth/user.json',
          },
          dependencies: ['setup'],
        }
      ],
    };
    
    export default config;
    
  2. 运行测试时明确指定项目,避免使用无认证状态的默认项目:
    npx playwright test --project=Chromium
    

验证测试页面跳转逻辑

  1. 检查PMSIntegrations.page里的navigateToIntegrations()方法,确保使用相对路径(配合baseURL)或正确的绝对路径:
    // 示例实现
    async navigateToIntegrations() {
      await this.page.goto('/integrations'); // 相对路径,依赖baseURL
      // 或者绝对路径:await this.page.goto('https://你的应用域名.com/integrations');
    }
    
  2. 可添加调试代码验证会话是否加载成功:
    test('User can integrate with third parties', async ({ page }) => {
      // 调试:查看当前页面的Cookie,确认认证状态是否加载
      const cookies = await page.context().cookies();
      console.log('当前Cookie:', cookies);
    
      const pmsIntegrationsPage = new PMSIntegrations(page);
      await pmsIntegrationsPage.navigateToIntegrations();
    
      expect(await pmsIntegrationsPage.areServicesConnected()).toBe(true);
    });
    

排查Cookie有效性

  1. 检查user.json里的Cookie是否包含正确的域名、路径和过期时间,避免因域名不匹配(比如localhost和127.0.0.1)导致Cookie无效。
  2. 如果应用使用localStorage存储认证信息,确认user.json里的origins字段包含对应域名的localStorage数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:10:18