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

如何在Postman中选取数组首个对象并校验其属性值

Postman测试:校验返回数组首个对象的gender属性值为"M"

正确测试代码

pm.test("首个对象gender为男性", () => {
    const jsonData = pm.response.json();
    // 先确保响应是数组且不为空,避免空数组报错
    expect(jsonData).to.be.an('array').that.is.not.empty;
    // 校验数组第一个对象的gender属性值为"M"
    expect(jsonData[0]).to.have.property('gender', 'M');
});

原代码问题分析

你写的代码里有两个关键错误:

  1. 断言时用了自己创建的{'gender': 1}对象,完全没用到Postman返回的响应数据jsonData,等于没校验接口返回内容
  2. 没有正确访问数组的第一个元素,要获取数组首个对象得用jsonData[0],而不是凭空构造对象

额外说明

加一句expect(jsonData).to.be.an('array').that.is.not.empty是做前置校验——如果接口返回空数组或者非数组格式,测试会直接提示这个问题,而不是卡在gender属性的断言上,排查问题更直观。

内容的提问来源于stack exchange,提问作者Иван Юмерски

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:45:02