如何验证chai中的响应键

How to verify the response key in chai

我有一个响应正文

[{
  "_id": "56fc22f625311b661becefb5",
  “activities”: [...],
  "lastName": “patrick”,
  "firstName": "John”,
  "city": “Chennai”,
  "state": “TAMILNADU”
}, {
  "_id": "56fc22f625311b661becefb6",
  “activities”: [...],
  "lastName": “sparrow”,
  "firstName": "John",
  "city": “Chennai”,
  "state": “TAMILNADU”
}]

当我在 Mocha 中通过超级测试进行 API 调用时,我必须验证响应主体的键是否具有 firstName、lastName 和 state,以及 state 的值是否为 chai 中的 TAMILNADU。

怎么做,我试过了

res.body.should.have.property("lastName");
res.body.should.have.property("state"); 

但出现错误

Uncaught AssertionError: expected [ Array(1) ] to have a property 'firstName'

您的正文包含一个数组,而不是一个对象,因此您需要像这样访问数组的第一个元素(未测试)

res.body[0].should.have.property("lastName");
res.body[0].should.have.property("state");

由于您的数组可以包含多个元素,因此您应该遍历数组

res.body.forEach((item) => {
    item.should.have.property("lastName");
    item.should.have.property("state");
})