Postman响应体类型校验报AssertionError,求错误原因排查
问题:Postman测试脚本断言报错原因分析
接口返回的响应体如下:
{ "data": { "id": 2, "email": "janet.weaver@reqres.in", "first_name": "Janet", "last_name": "Weaver", "avatar": "https://reqres.in/img/faces/2-image.jpg" }, "support": { "url": "https://reqres.in/#support-heading", "text": "To keep ReqRes free, contributions towards server costs are appreciated!" } }
为校验响应体的数据类型,编写的Postman测试脚本如下:
const jsonData= pm.response.json(); pm.test("testing type in the response body", () =>{ pm.expect(jsonData).to.be.an("object"); pm.expect(jsonData.data).to.be.an("object"); pm.expect(jsonData.id).to.be.a("number"); pm.expect(jsonData.email).to.be.a("string"); pm.expect(jsonData.first_name).to.be.a("string"); pm.expect(jsonData.last_name).to.be.a("string") });
运行脚本时出现以下错误:
testing type in the response body | AssertionError: expected undefined to be a number
testing type in the response body | AssertionError: expected undefined to be a string
错误原因
你在断言jsonData.id、jsonData.email等字段时,直接从根对象jsonData获取属性,但这些字段实际嵌套在jsonData.data对象内部,根对象本身不存在这些属性,访问它们会返回undefined,因此断言失败。
修正后的测试脚本
将字段路径改为从jsonData.data开始,同时可以补充完整的类型校验:
const jsonData= pm.response.json(); pm.test("testing type in the response body", () =>{ pm.expect(jsonData).to.be.an("object"); pm.expect(jsonData.data).to.be.an("object"); pm.expect(jsonData.data.id).to.be.a("number"); pm.expect(jsonData.data.email).to.be.a("string"); pm.expect(jsonData.data.first_name).to.be.a("string"); pm.expect(jsonData.data.last_name).to.be.a("string"); pm.expect(jsonData.data.avatar).to.be.a("string"); pm.expect(jsonData.support).to.be.an("object"); pm.expect(jsonData.support.url).to.be.a("string"); pm.expect(jsonData.support.text).to.be.a("string"); });
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

