如何在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'); });
原代码问题分析
你写的代码里有两个关键错误:
- 断言时用了自己创建的
{'gender': 1}对象,完全没用到Postman返回的响应数据jsonData,等于没校验接口返回内容 - 没有正确访问数组的第一个元素,要获取数组首个对象得用
jsonData[0],而不是凭空构造对象
额外说明
加一句expect(jsonData).to.be.an('array').that.is.not.empty是做前置校验——如果接口返回空数组或者非数组格式,测试会直接提示这个问题,而不是卡在gender属性的断言上,排查问题更直观。
内容的提问来源于stack exchange,提问作者Иван Юмерски
相关产品推荐
相关产品推荐

