Need help to convert a working arrow function to a regular function to write unit tests

Viewed 46

I would like to convert the below working code

const Client = require('node-rest-client').Client;
const Rest = new Client();

const useRestClient = (url,args,_next)=> {
    return new Promise(resolve => {
        Rest.post(url,args, (data,_response) =>
            {
                resolve(data);
            })
        })
}

to something like this:

const Client = require('node-rest-client').Client;
const Rest = new Client();

function callRestPost(resolve, url, args) 
{
    return Rest.post(url,args, (data,_response) =>
            {
                resolve(data);
            });
}

const useRestClient = (url,args,_next)=> {
    return new Promise(callRestPost);
}

Is this correct? The reason I am doing is, is to mock the Rest.post method for unit testing. I am restricted to using mocha sinon for testing and I am new to JS and node.js. Please help.

2 Answers

You're close, you just have to pass in the args..

const Client = require('node-rest-client').Client;

function callRestPost(resolve, url, args) 
{
  return Rest.post(url,args, (data,_response) => {
    resolve(data);
  });
}

const useRestClient = (url,args,_next)=> {
  return new Promise((resolve, reject) => { 
    try {
      return callRestPost(resolve, url, args);
    } catch (err) {
      reject(err);
    }
  });
}

What's the reason for passing in the resolve, though?

IMO something like this is cleaner.

const Client = require('node-rest-client').Client;
const RestClient = new Client();

function callRestPost(restClient, url, args) {
  return new Promise((resolve, reject) => {
    try {
      restClient.post(url, args, (data, resp) => {
        if (resp.status !== 200) reject(resp.status);
        resolve(data);
      });
    } catch (err) {
      reject(err);
    }
  });
}

// Use it like:
callRestPost(RestClient, "some.url", [foo, bar, baz]);

I would re-write it like this.

const Client = require('node-rest-client').Client;
const Rest = new Client();

function callRestPost(resolve, url, args) {
  return Rest.post(url,args, function(data,_response) {
    resolve(data);
  });
}

function useRestClient(url,args,_next) {
  return new Promise(function(resolve) {
    return callRestPost(resolve, url, args)
  });
}

Related