REST API unit test with promise return in nodejs

867 Views Asked by At

I have a function in a class which invokes REST api and returns Promise object.I am able to test Promise object bu I am not sure how we can stub or mock rest api call and test.

Token.js

class Token {

  getToken(payload) {
    let outahToken = new Promise(function (resolve, reject) {
      request('hhtps://xyz.com', function (err, res, body) {
        if (err) {
          reject(err);
        } else {
          console.log(res);
          resolve(body);
        }
      })
    });

    return outahToken;
  }
}
module.exports = Token;

Token.test.js

'use strict'

const chai = require("chai");
const expect = chai.expect;
const nock = require('nock');
const sinon = require("sinon");
const Token = require('Token');
describe('Get User tests', () => {
  let Token;
  beforeEach(() => {
    outhController = new Token();
    sinon.stub(Token, 'getToken').returns(Promise.resolve({
      name: "All"
    }));

  });

  it('Outh test', (done) => {
    Token.getToken(payload)
      .then(response => {
        expect(typeof response).to.equal('object');
        done();
      });
  });
});        
1

There are 1 best solutions below

2
On BEST ANSWER

We can mock request module with proxyquire and check if it is being called with correct argument. We need proxyquire because request module export a function request() which harder to mock with Sinon only.

And because request method is a callback function, we can use Sinon yields to mock it.

const chai = require('chai');
const sinon = require('sinon');
const proxyquire = require('proxyquire');

const expect = chai.expect;

describe('Token test', function() {
  let outhController;
  let Token;
  let requestStub;

  beforeEach(() => {
    const err = null;
    const res = null;
    const body = { name: 'All' };

    requestStub = sinon.stub().yields(err, res, body); // create sinon for request function and return response body that we want
    Token = proxyquire('Token', { request: requestStub }) // replace original request module with our sinon stub

    outhController = new Token();
  });

  it('Outh test', (done) => {
    const payload = {};
    outhController.getToken(payload)
      .then(response => {
        sinon.assert.calledWith(requestStub, 'hhtps://xyz.com');

        expect(typeof response).to.equal('object');
        expect(response.name).to.equal('All');

        done();
      });
  });
});

Hope it helps