Daniel S
Daniel S

Reputation: 13

How do I validate the nested response object with mocha and chai assertion

I am using chai and mocha to test for one of my Node.js. The Assertions I am trying to use is throwing error.

Uncaught AssertionError: expected { Object (_events, _eventsCount, ...) } to have property 'address'

Trying to validate the below response objects and values with assertion:

Json Response body

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

Code

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();
         });
       });             

Upvotes: 0

Views: 2102

Answers (1)

Wodlo
Wodlo

Reputation: 937

res has a body property but it does not have all the other properties you are expecting, those are found within the body.

try

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")); 

Upvotes: 1

Related Questions