Nodejs Mocha Test for Valid JSON

Mocha

This is how you can use the Node.js test suite Mocha to Test for Valid JSON. This could come in handy when testing if API’s are returning valid JSON – essential part of your web application integration testing.

Note: I’ve taken this testing concept further and added tests for JSON Schema as well. See Mocha Test JSON Schema is Valid to see how you might do it.

http.get('http://localhost:8000', function (res) {

    it("should respond with status code 200", function () {
        expect(res.response.statusCode).to.equal(200);
    });

    it("should respond with valid JSON", function () {
        res.response.should.be.json;
    });

});

Supertest

OR you could use Supertest node.js library which is awesome at testing JavaScript. This is how you might use it to test for a valid JSON response from your back-end API.

var url = 'http://localhost:8000';
request(url)
    .get('feed/?token=4JmWChUedgfWAZ5NUNIMXcVR&feed=http://angularjs4u.com/?feed=rss2')
    .expect('Content-Type', /json/)
    .expect(200) //Status code
    .end(function (err, res) {
        if (err) {
            throw err;
        }
        // Should.js fluent syntax applied
        res.body.should.have.property('_id');
        res.body.firstName.should.equal('Sam');
        res.body.lastName.should.equal('Deering');
        res.body.creationDate.should.not.equal(null);
        done();
    });