ChrisRTech
ChrisRTech

Reputation: 577

Sinon stub request-promise for client unit test

I have a Node.js HTTP client that uses request-promise to do GETs and PUTs against a remote service. The client code is below. I'm trying write a unit tests and stub the requestPromise(options) call so that I get back a dummy response like:

{
  statusCode: 200,
  body: "Dummy Reponse"
}

Here my client:

module.exports.getSensorData = async function(parms) {
    let response = {};
    let endpoint = null;
    try {
        endpoint = buildGetURL(parms);
        var options = {
            method: 'GET',
            uri: endpoint,
            json: false,
            resolveWithFullResponse: true
        };
        console.log(`Connecting to Service at: ${endpoint}`);
        let serviceResponse = await requestPromise(options); <-- stub this
        response.statusCode = serviceResponse.statusCode;
        response.body = serviceResponse.body;
    } catch (err) {
        let msg = `Service Client Error ${endpoint}`;
        response.statusCode = 500;
    }

    // Done
    return response;
}

I've tried some things with Sinon but I'm not clear how to do this. Ideally I want something like this in my unit test:

const sinon = require('sinon');
const requestPromise = require('request-promise');
const serviceClient = require("../ServiceClient");
let sandbox = null;
describe("Test My Client", function() {

  beforeEach(function() {
    sandbox = sinon.createSandbox();

    sandbox.stub(requestPromise).callsFake(options) => {
      return {
        statusCode: 200,
        body: "Dummy Response"
      }
    });

  });
  afterEach(function() {
    sandbox.restore();
  });

  it("My Client Test", (done) => {
    serviceClient.getSensorData(parms) 
      .then(function(response) {
        assert.equal(response.statusCode,200);
        assert.equal(response.body,"Dummy Response");
      }
  });

Upvotes: 0

Views: 1260

Answers (1)

ChrisRTech
ChrisRTech

Reputation: 577

This does it:

   beforeEach(function() {
        console.log("=== TestServiceClient BEFORE EACH =====");
        sandbox = sinon.createSandbox();
        sandbox.stub(requestPromise, 'Request').resolves({
            statusCode: 200,
            body: "Dummy Response"
        }); 
    });

Upvotes: 1

Related Questions