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

如何编写Postman的pm.test断言?Jenkins/Newman执行报错求助

问题解决:Postman/Newman断言接口响应字段的兼容写法

接口返回JSON结构

{
    "data": {
        "clearEmployerClaim": true
    }
}

两种写法的问题分析

第一种写法失效原因

原代码直接访问response.clearEmployerClaim,但目标字段实际嵌套在data对象下,导致读取值为undefined,断言自然不生效。

第二种写法在Newman中报错原因

Postman环境会自动将body解析为JSON对象,但Newman中body可能仍是字符串类型,直接访问body.data会触发类型错误。

修正后的可行写法

写法一(使用pm.expect,全环境兼容)

修正字段访问层级,确保正确读取目标值:

pm.test("clear employer claim status returned", () => { 
    const response = pm.response.json(); 
    pm.expect(response.data.clearEmployerClaim).to.be.true;
});

写法二(兼容Postman和Newman的传统tests写法)

手动解析响应体为JSON对象,避免环境差异:

const response = pm.response.json();
tests["C536773447 clear employer claim status returned"] = response.data.clearEmployerClaim === true;

也可以显式解析响应文本:

const responseBody = JSON.parse(pm.response.text());
tests["C536773447 clear employer claim status returned"] = responseBody.data.clearEmployerClaim === true;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:05:16