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

在Playwright中测试HTTP状态码遇response未定义问题求助

如何在Playwright中捕获并验证HTTP响应状态码

你遇到的问题核心是没有提前捕获到请求对应的response对象,直接调用response.status()自然会报错。下面提供两种可行的解决方法:

方法一:通过页面监听捕获响应

在执行触发目标请求的操作前,先监听页面的响应事件,筛选出你需要验证的请求,再捕获其response:

test.only('Rights.2: Users without the required author role do not have access.', async ({page}) => {
    await login(page, 'xxx', "password.xxx");
    const search = await searchForProcess(page, `${process.process1.title}`);
    await login(page, 'PortalUser');

    // 提前监听目标请求的响应,根据实际请求的URL/方法筛选
    const responsePromise = page.waitForResponse(response => 
        response.url().includes('/process/') && response.request().method() === 'GET'
    );

    // 执行触发请求的操作
    const open = await openProcess(page, `${process.process1.title}`);

    // 获取捕获到的响应对象
    const response = await responsePromise;

    // 验证403状态码
    expect(response.status()).toBe(403);
});

方法二:从操作函数中直接返回响应

如果你的openProcess函数是通过page.goto或page.click触发请求,可以修改函数让它直接返回响应对象:

先调整openProcess函数:

async function openProcess(page: Page, title: string): Promise<Response | null> {
    // 示例:点击元素触发导航,返回响应
    return page.click(`text=${title}`, { waitFor: 'networkidle' });
    // 若是用goto跳转:return page.goto(`/process/${title}`);
}

然后在测试中直接接收并验证:

test.only('Rights.2: Users without the required author role do not have access.', async ({page}) => {
    await login(page, 'xxx', "password.xxx");
    const search = await searchForProcess(page, `${process.process1.title}`);
    await login(page, 'PortalUser');

    // 获取操作返回的响应对象
    const response = await openProcess(page, `${process.process1.title}`);

    // 验证状态码(注意判断response不为空)
    expect(response?.status()).toBe(403);
});

注意事项

  • 使用page.waitForResponse时,务必精准筛选请求(比如URL包含特定路径、请求方法匹配等),避免捕获到无关响应导致断言失败。
  • 若是SPA的AJAX请求,同样可以用waitForResponse捕获,只需匹配对应的请求特征即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:20:40