【问题标题】:Mocha Chai check if Json response contains specific propertyMocha Chai 检查 Json 响应是否包含特定属性
【发布时间】:2019-07-30 15:26:36
【问题描述】:

我正在创建 API 测试,用于检查响应是否在结构中包含特定键“textId”:

  it('TC-4 /rest/passwords/ should change "password"', function() {
    return chai.request(serverurl)
      .post('/rest/passwords/')
      .set('Content-Type', 'application/json')
      .set('Accept', 'text/html')
      .set('X-Api-Key', global.apikey)
      .set('Cookie', global.cookie)
      .send({password: "password"})
      .then(function(res) {
        res.should.have.status(200);
        res.should.be.json;
        console.log('TC-4 /rest/passwords/: %j\n', res.body);
        res.body.should.have.all.keys(['textId']);
      });
  });

回复如下:

[{"textId":"PasswordNeedsAtLeastOneDigit","parameters":{}},{"textId":"PasswordNeedsAtLeastOneUpperCaseCharacter","parameters":{}}]

我试过了:

res.body.should.have.property('textId');
res.body.should.have.nested.property('textId');
res.body.should.have.all.keys(['textId']);
res.body.should.have.all.nested.keys(['textId']);

它们都不起作用

【问题讨论】:

  • 主体没有 例如具有该属性,它包含一个具有该属性的对象。身体是一个数组,试试例如res.body[0].should... 或使用数组匹配器。
  • res.body[0].should... 返回无法读取未定义的“应该”属性,但现在我发现这可以正常工作res.body.should.have.nested.property('[0].textId'); 感谢 jonrsharpe

标签: mocha.js chai jsonpath chai-http


【解决方案1】:

有点晚了,但对于任何未来的观众,你需要这样的东西:

res.body.should.have.property('data').that.includes.all.keys(['status', 'id', 'name', 'email',
          'bio', 'image', 'email_verified', 'role', 'isActive', 'isDeleted', 'createdAt', 'updatedAt', 'token']);

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2023-03-07
    • 2015-12-19
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多