Search code examples
node.jsunit-testingnock

How to return a invalid Buffer in order to test an API call?


I'm currently learning how to write unit tests in Node.js. For this i have made a small file that can make an API call:

const https = require('https')
module.exports.doARequest = function (params, postData) {
  return new Promise((resolve, reject) => {
    const req = https.request(params, (res) => {
      let body = []
      res.on('data', (chunk) => {
        body.push(chunk)
      })
      res.on('end', () => {
        try {
          body = JSON.parse(Buffer.concat(body).toString())
        } catch (e) {
          reject(e) //How can i test if the promise rejects here?
        }
        resolve(body)
      })
    })
    req.end()
  })
}

In order to test the happy flow of this file i have faked a request using nock. However i would like test if JSON.parse throws an error. For this i think i have to fake the data that's inside Buffer.concat(body).toString(). The fake data should be something JSON.parse cannot parse. That way i can test if the promise gets rejected. Only question is, how do i do this?

Test file corresponding to the doARequest module above:

const chai = require('chai');
const nock = require('nock');
const expect = chai.expect;

const doARequest = require('../doARequest.js');

describe('The setParams function ', function () {
  beforeEach(() => {
    nock('https://stackoverflow.com').get('/').reply(200, { message: true })
  });

  it('Goes trough the happy flow', async () => {
    return doARequest.doARequest('https://stackoverflow.com/').then((res) => {
      expect(res.message).to.be.equal(true)
    });
  });

  it('Rejects when there is an error in JSON.parse', async () => {
    //How can i test this part?
  });
});

Any help/suggestions will be appreciated.


Solution

  • Right now you are using nock's shorthand for passing back an object, i.e., this line:

    nock('https://stackoverflow.com').get('/').reply(200, { message: true });
    

    It's the same as passing back a JSON string, or:

    nock('https://stackoverflow.com').get('/').reply(200, JSON.stringify({
        message: true
    }));
    

    To force JSON.parse to fail, just pass back a string that is not valid JSON, e.g.:

    nock('https://stackoverflow.com').get('/').reply(200, 'bad');