Test how API handles invalid JSON syntax request body using node.js

alefteris picture alefteris · Feb 2, 2015 · Viewed 7k times · Source

I would like to test how an REST API handles a POST request that has a body with invalid JSON syntax, for example a missing comma. I'm using node.js to write the API tests. I'm using frisby but I also tried supertest. No luck. With the previous tools, you pass the request body as a JavaScript object, so it's no go. I tried also to pass the invalid JSON as a string without any luck, since a string is also valid JSON (example below). Any ideas?

frisby.create('Ensure response has right status')
    .post('http://example.com/api/books', '{"invalid"}', {json: true})
    .expectStatus(400)
    .toss();

Answer

alefteris picture alefteris · Feb 13, 2015

Using the supertest and mocha packages, you can test an endpoint by posting the invalid JSON like this:

var request = require('supertest');

describe('Adding new book', function(){
  it('with invalid json returns a 400', function(done){
    request('http://example.com').post('/api/books')
      .send('{"invalid"}')
      .type('json')
      .expect('Content-Type', /json/)
      .expect(400)
      .end(function(err, res) {
          console.log(res.error);
          done();
      });
  });
});

The important bit here is type(json). This will set the Content-Type of the request to application/json. With out it, supertest/superagent will default to sending strings as application/x-www-form-urlencoded. Also the invalid JSON is provided as a string and not as a JavaScript object.