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

如何将Playwright Response Body转为字符串?无需重复使用await

问题解决:Playwright中响应体字符串的正确存储与比较

问题根源

你遇到的问题核心是异步操作顺序处理错误:response.body()返回的是Promise<Buffer>,你直接在后面链式调用.toString(),实际上是对Promise对象调用了toString方法,而非等待Promise resolve后对Buffer调用toString,这就导致responseBody变成了字符串"[object Promise]",而非真正的响应体内容。

两种正确解决方法

方法1:先等待Buffer返回,再转字符串

调整获取响应体的代码,先通过await拿到Buffer,再调用.toString()转成字符串:

test.describe("Update Existing User in ReqRes",()=>{
    test("Update user",async ({request})=>{
        const playload = {
            "name": "Shin chan",
            "job": "lifetime president"
        }

        const response = await request.put("/api/users/2",{data:playload});
        // 先await拿到Buffer,再转字符串
        const responseBody : string = (await response.body()).toString(); 
        console.log("The Response We got for the PUT Request\n",responseBody);
        await expect(response.status()).toBe(200);
        // 现在可直接用responseBody做比较
        expect(responseBody).toContain("Shin chan"); 
        expect(responseBody).toContain("lifetime president");
    })
})

方法2:直接使用response.text()(更简洁)

Playwright的response对象提供了text()方法,会直接返回Promise<string>,省去手动转Buffer的步骤:

test.describe("Update Existing User in ReqRes",()=>{
    test("Update user",async ({request})=>{
        const playload = {
            "name": "Shin chan",
            "job": "lifetime president"
        }

        const response = await request.put("/api/users/2",{data:playload});
        // 直接用text()获取字符串
        const responseBody : string = await response.text(); 
        console.log("The Response We got for the PUT Request\n",responseBody);
        await expect(response.status()).toBe(200);
        expect(responseBody).toContain("Shin chan");
        expect(responseBody).toContain("lifetime president");
    })
})

额外注意点

  • 对比时不需要加await,因为responseBody已经是同步的字符串,expect对字符串的断言是同步操作。
  • 之前的错误提示Received string: "[object Promise]",就是因为你直接把Promise对象转成了字符串,而非等待它resolve后拿到实际响应内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:11:12