jsonnode.jsmocha.jssupertestshould.js

Error when trying to read JSON array using Should, Mocha, & Supertest


I have the following JSON payload:

"app": {
    "name": "myapp",
    "version": "1.0.0",
    "last_commit": {
        "author_name": "Jon Snow"
        "author_email": "my@email.com"
    }
}

and the following .js file (using Mocha, Supertest and Should):

var supertest = require('supertest')
var should = require('should')
var server = supertest.agent('http://localhost:3001')

describe('GET /', function () {
    it('should respond with JSON', function (done) {
        server
            .get('/')
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect(200)
            .end(function (err, res) {
                var payload = res.body.app;
                payload.should.have.property("app");
                payload.should.have.property("name");
                payload.should.have.property("version");
                payload.should.have.property("last_commit");
                payload.should.have.property("last_commit.author_name");
                payload.should.have.property("last_commit.author_email");
                done();
            });
    });
});

When I test the app, I receive the following error message:

Uncaught AssertionError: expected Object {
    "name": "myapp",
    "version": "1.0.0",
    "last_commit": Object {
        "author_name": "Jon Snow"
        "author_email": "my@email.com"
    }
} to have property 'last_commit.author_name'

Why am I receiving an assertion error on the these lines?

payload.should.have.property("last_commit.author_name");
payload.should.have.property("last_commit.author_email");

Solution

  • Assertion is looking for a property called last_commit.author_name which is not present. You may want to break that into two assertions.

    payload.should.have.property("last_commit");
    let last_commit = payload.last_commit;
    last_commit.have.property("author_name");