使用Postman BDD/Chai测试返回数组的REST API属性检查问题
用Postman/Chai测试数组格式API响应的解决方案
刚好碰到过类似的场景,我来给你捋捋怎么解决~你之前用expect(response).to.have.property('id')失效,是因为整个响应是数组类型,而不是单个对象,数组本身并没有id这个属性,所以得换针对数组的断言方式。
根据你要检查的具体需求,这里分几种常用情况:
1. 检查数组中存在某个完整的目标对象
如果你要确认响应数组里包含某一个特定的完整用户对象(比如id=1的那个用户),可以用Chai的include.deep.members来做深度比较(因为对象是引用类型,浅比较会判断不通过):
const responseData = pm.response.json(); // 先把响应转成数组 expect(responseData).to.include.deep.members([ { "id": 1, "firstName": "x", "lastName": "y", "dateOfBirth": "2018-04-21", "username": "user" } ]);
2. 检查数组中存在满足特定条件的元素
如果不需要匹配完整对象,只需要确认数组里有符合某个条件的元素(比如存在username=admin的用户,或者id=2的用户),有两种方式:
方式一:用原生JS的some方法结合断言
这种方法不需要额外插件,直接用数组的some方法判断是否存在符合条件的元素,再用Chai断言结果为true:
const responseData = pm.response.json(); // 检查是否存在id=2的用户 const hasTargetUser = responseData.some(user => user.id === 2); expect(hasTargetUser).to.be.true; // 或者检查是否存在username为"admin"的用户 const hasAdmin = responseData.some(user => user.username === "admin"); expect(hasAdmin).to.be.true;
方式二:用chai-things插件简化写法
如果你觉得上面的写法有点繁琐,可以用Chai的chai-things插件(需要确保Postman里能引入,一般可以在测试脚本里先导入),这样代码更简洁:
const chai = require('chai'); const chaiThings = require('chai-things'); chai.use(chaiThings); const responseData = pm.response.json(); // 检查数组中存在id=1的元素 expect(responseData).to.include.something.with.property('id', 1); // 检查数组中存在username为"admin"的元素 expect(responseData).to.include.something.with.property('username', 'admin');
3. 检查数组中所有元素都包含某个属性
如果你的需求是确认数组里的每一个用户对象都有id这个属性(比如校验接口返回格式的完整性),可以用every方法或者chai-things的all断言:
const responseData = pm.response.json(); // 原生JS方式 const allHaveId = responseData.every(user => user.hasOwnProperty('id')); expect(allHaveId).to.be.true; // chai-things方式 expect(responseData).to.all.have.property('id');
内容的提问来源于stack exchange,提问作者Lithicas
相关产品推荐
相关产品推荐

