GianMS
GianMS

Reputation: 983

How to check if the response's body has certain properties in one single assertion in Mocha

I'm testing a web applications' routers in Node.js using Mocha and I was wondering if there is a way to check in one single assert if an object has certain properties.

Right now, this is what I'm doing:

describe('GET /categories', function () {
        it('should respond with 200 and return a list of categories', function (done) {
            request.get('/categories')
                .set('Authorization', 'Basic ' + new Buffer(tokenLogin).toString('base64'))
                .expect('Content-Type', /json/)
                .expect(200)
                .end(function (err, res) {
                    if (err) return done(err);
                    expect(res.body).to.be.an.instanceof(Array);
                    expect(res.body).to.have.lengthOf.above(0);
                    expect(res.body[0]).to.have.property('id');
                    expect(res.body[0]).to.have.property('category');
                    expect(res.body[0]).to.have.property('tenant');
                    done();
                });
        });
});

I've searched in Mocha's documentation, but I haven't been able to find what I want.

Upvotes: 5

Views: 11995

Answers (1)

robertklep
robertklep

Reputation: 203319

I assume that you're using chai:

expect(res.body)
  .to.be.an.instanceof(Array)
  .and.to.have.property(0)
  .that.includes.all.keys([ 'id', 'category', 'tenant' ])

Or:

expect(res)
  .to.have.nested.property('body[0]')
  .that.includes.all.keys([ 'id', 'category', 'tenant' ])

(although the latter doesn't really check if res.body is actually an array)

Upvotes: 7

Related Questions