【问题标题】:How do I validate the nested response object with mocha and chai assertion如何使用 mocha 和 chai 断言验证嵌套响应对象
【发布时间】:2021-01-21 19:47:10
【问题描述】:

我正在使用 chai 和 mocha 来测试我的 Node.js 之一。 我尝试使用的断言抛出错误。

未捕获的 AssertionError:预期 { Object (_events, _eventsCount, ...) } 具有属性“地址”

尝试使用断言验证以下响应对象和值:

Json 响应正文

{
  "address": "value1",
  "testware": "value2",
  "status": false,
  "linestatus": "online",
  "optionalstatus": {
                        "line1": "offline",
                        "line2": "offline",
  }
}

代码

describe('GET /getstatus Success Response (200)', () => {
        it('Should return Status of line', (done) => {
         chai.request(endpoint)
           .get(getUrlWithQueryParamString({"url": "Passing get URL here", "method":"GET"}))
           .end((err, res) => {
              //console.log(res);
              expect(res).to.have.status(200);
              expect(res).to.have.property("body")
                        .and.have.property("address").equal("value1")
                        .and.have.property("testware").equal("value2")
                        .and.have.property("status").equal(false)
                        .and.have.property("linestatus").equal("online")
               expect(res.body.optionalstatus.line1.to.include("offline")); 
            done();
         });
       });             

【问题讨论】:

    标签: node.js mocha.js chai


    【解决方案1】:

    res 有一个 body 属性,但它没有您期望的所有其他属性,这些属性在正文中找到。

    试试

    expect(res).to.have.property("body");
    expect(res.body).to.have.property("address").equal("value1")
            .and.have.property("testware").equal("value2")
            .and.have.property("status").equal(false)
            .and.have.property("linestatus").equal("online")
    expect(res.body.optionalstatus.line1.to.include("offline")); 
    

    【讨论】:

    • 尝试了上述更改..但是仍然出现错误...未捕获的 AssertionError: 预期 'value1' 具有属性 'testware'
    • 这真的很有帮助。找到了上面代码的修复方法。
    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 2012-07-16
    • 2023-04-02
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 2023-03-04
    相关资源
    最近更新 更多