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

K6浏览器测试页面重定向异常问题求助

解决K6浏览器测试中页面重定向后标题获取异常的问题

核心问题分析

  • page.waitForNavigation() 默认仅等待单次跳转完成,若登录后存在多次链式重定向,会导致等待提前结束,后续页面加载未被捕获
  • 固定时长的sleep()无法适配不同环境的加载速度,要么等待不足要么浪费时间
  • 未正确使用异步方法:page.title() 是异步函数,直接调用无法获取实际标题内容

修复方案

1. 增强导航等待的可靠性

每次调用waitForNavigation()时,明确指定waitUntil和timeout参数,覆盖页面加载的完整周期,同时确保等待与点击操作的Promise.all顺序正确(避免点击后才开始等待)。

2. 用元素等待替代固定sleep

跳转完成后,等待目标页面的标志性元素出现,确保页面完全加载完成,而非依赖固定时长休眠。

3. 正确异步调用page.title()

必须使用await获取页面标题,否则无法拿到实际的页面标题内容。

修改后的测试代码

import { chromium } from 'k6/experimental/browser';
import { check } from 'k6';

export const options = {
  maxRedirects: 20,
  scenarios: {
    browser: {
      executor: 'shared-iterations',
      exec: 'browser',
      vus: 1,
      maxDuration: '1m',
    },
  },
};

export async function browser() {
  const browser = chromium.launch({ headless: false, timeout: '120s', slowMo: '500ms' });
  const context = browser.newContext();
  const page = context.newPage();

  // 初始页面加载,等待网络空闲
  await page.goto('http://localhost:5000/', { waitUntil: 'networkidle', timeout: '60s' });

  // 处理Cookie弹窗
  const cookieButton = page.locator('#cookies-banner div div:nth-child(2) button');
  await cookieButton.click();
  await page.waitForLoadState('networkidle'); // 等待弹窗关闭后的页面稳定

  // 输入公司名称并跳转
  await page.locator('#company-input').type('Test1');
  const continueButton = page.locator('#company-login-continue-button');
  
  await Promise.all([
    page.waitForNavigation({ waitUntil: 'networkidle', timeout: '60s' }),
    continueButton.click(),
  ]);

  // 选择密码登录方式并跳转
  const loginButton = page.locator('#login-method-selection-password-login-button p');
  await Promise.all([
    page.waitForNavigation({ waitUntil: 'networkidle', timeout: '60s' }),
    loginButton.click(),
  ]);

  // 输入账号密码并提交
  await page.locator('#user-name-input').type('TestUsername');
  await page.locator('#password-input').type('TestPassword');
  const continueButton2 = page.locator('#password-login-continue-button p');

  // 关键:登录后可能存在多次重定向,等待直到网络完全空闲
  await Promise.all([
    page.waitForNavigation({ waitUntil: 'networkidle', timeout: '60s' }),
    continueButton2.click(),
  ]);

  // 额外等待目标页面的标志性元素,确保页面完全加载
  await page.waitForSelector('.dashboard-header', { timeout: '30s' }); // 替换为你目标页面的元素选择器

  // 正确异步获取页面标题
  const pageTitle = await page.title();
  console.log('最终页面标题:', pageTitle);

  // 可选:添加断言验证标题
  check(pageTitle, {
    '最终页面标题正确': (title) => title.includes('预期标题关键词'),
  });

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

额外注意事项

  • 替换代码中的.dashboard-header为你登录后目标页面的唯一标志性元素,确保页面已完全渲染
  • 调整timeout参数适配你的页面加载速度,避免因超时导致测试失败
  • 避免在测试中过度依赖sleep(),优先使用基于元素或状态的等待方式,提升测试稳定性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:01:12