使用Postman验证数据时遇TypeError:无法读取undefined属性
问题解决方法
错误原因
报错Cannot read properties of undefined (reading 'gender')和Cannot read properties of undefined (reading 'fullName'),核心是你直接访问response.naturalPerson,但从接口返回的JSON结构来看,naturalPerson嵌套在party对象下,response.naturalPerson会返回undefined,自然无法读取它的子属性。
修复后的测试代码
将访问路径修正为response.party.naturalPerson即可,修改后的代码如下:
const response = pm.response.json(); pm.test("Check value is either 1 or 2", function() { pm.expect(response.party.naturalPerson.gender).to.be.oneOf([1, 2]); }); pm.test("Check value fullName", function() { pm.expect(response.party.naturalPerson.fullName).to.eql("Bia Teste"); });
额外优化建议(可选)
为避免后续类似层级访问错误,可先校验父级对象是否存在,提前定位结构问题:
pm.test("Check party and naturalPerson exist", function() { pm.expect(response).to.have.property('party'); pm.expect(response.party).to.have.property('naturalPerson'); });
内容的提问来源于stack exchange,提问作者Staulik
相关产品推荐
相关产品推荐

