Node.js - How to test HTTPS requests with promise












0















I started writing unit tests for my nodeJs application so i could learn about this concept.
After writing some basic tests for simple functions (using Mocha and Chai) i want to move on to some more complex tests.



I have written a simple piece of code that can make a request using node's HTTPS module. That code looks like this:



const https = require('https')
module.exports.doRequest = 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)
}
resolve(body)
})
})
req.on('error', (err) => {
reject(err)
})
if (postData) {
req.write(JSON.stringify(postData))
}
req.end()
})
}


Now i want to invoke this method with the following parameters:



const PARAMS = {
host: 'jsonplaceholder.typicode.com',
port: 433,
method: 'GET',
path: `/todos/1`,
headers: {
Authorization: 'Bearer 123'
}
}


And make the request like so:



getTodos = (PARAMS) => {
return doRequest(PARAMS).then((result) => {
if (result.errors) { throw result }
return {
'statusCode': 200,
'body': JSON.stringify({ message: result.title }),
}
}).catch((error) => ({
'statusCode': error.statusCode,
'body': JSON.stringify({ message: error.message }),
}
))
}


Now my question is how i can test this bit of code properly. I have looked on how to tackle this with the Nock.js libary but i don't have a good understanding on where to start.
If anyone can point me in the right direction on how to start with writing some tests for this bit of code i will be thankfull.










share|improve this question



























    0















    I started writing unit tests for my nodeJs application so i could learn about this concept.
    After writing some basic tests for simple functions (using Mocha and Chai) i want to move on to some more complex tests.



    I have written a simple piece of code that can make a request using node's HTTPS module. That code looks like this:



    const https = require('https')
    module.exports.doRequest = 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)
    }
    resolve(body)
    })
    })
    req.on('error', (err) => {
    reject(err)
    })
    if (postData) {
    req.write(JSON.stringify(postData))
    }
    req.end()
    })
    }


    Now i want to invoke this method with the following parameters:



    const PARAMS = {
    host: 'jsonplaceholder.typicode.com',
    port: 433,
    method: 'GET',
    path: `/todos/1`,
    headers: {
    Authorization: 'Bearer 123'
    }
    }


    And make the request like so:



    getTodos = (PARAMS) => {
    return doRequest(PARAMS).then((result) => {
    if (result.errors) { throw result }
    return {
    'statusCode': 200,
    'body': JSON.stringify({ message: result.title }),
    }
    }).catch((error) => ({
    'statusCode': error.statusCode,
    'body': JSON.stringify({ message: error.message }),
    }
    ))
    }


    Now my question is how i can test this bit of code properly. I have looked on how to tackle this with the Nock.js libary but i don't have a good understanding on where to start.
    If anyone can point me in the right direction on how to start with writing some tests for this bit of code i will be thankfull.










    share|improve this question

























      0












      0








      0








      I started writing unit tests for my nodeJs application so i could learn about this concept.
      After writing some basic tests for simple functions (using Mocha and Chai) i want to move on to some more complex tests.



      I have written a simple piece of code that can make a request using node's HTTPS module. That code looks like this:



      const https = require('https')
      module.exports.doRequest = 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)
      }
      resolve(body)
      })
      })
      req.on('error', (err) => {
      reject(err)
      })
      if (postData) {
      req.write(JSON.stringify(postData))
      }
      req.end()
      })
      }


      Now i want to invoke this method with the following parameters:



      const PARAMS = {
      host: 'jsonplaceholder.typicode.com',
      port: 433,
      method: 'GET',
      path: `/todos/1`,
      headers: {
      Authorization: 'Bearer 123'
      }
      }


      And make the request like so:



      getTodos = (PARAMS) => {
      return doRequest(PARAMS).then((result) => {
      if (result.errors) { throw result }
      return {
      'statusCode': 200,
      'body': JSON.stringify({ message: result.title }),
      }
      }).catch((error) => ({
      'statusCode': error.statusCode,
      'body': JSON.stringify({ message: error.message }),
      }
      ))
      }


      Now my question is how i can test this bit of code properly. I have looked on how to tackle this with the Nock.js libary but i don't have a good understanding on where to start.
      If anyone can point me in the right direction on how to start with writing some tests for this bit of code i will be thankfull.










      share|improve this question














      I started writing unit tests for my nodeJs application so i could learn about this concept.
      After writing some basic tests for simple functions (using Mocha and Chai) i want to move on to some more complex tests.



      I have written a simple piece of code that can make a request using node's HTTPS module. That code looks like this:



      const https = require('https')
      module.exports.doRequest = 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)
      }
      resolve(body)
      })
      })
      req.on('error', (err) => {
      reject(err)
      })
      if (postData) {
      req.write(JSON.stringify(postData))
      }
      req.end()
      })
      }


      Now i want to invoke this method with the following parameters:



      const PARAMS = {
      host: 'jsonplaceholder.typicode.com',
      port: 433,
      method: 'GET',
      path: `/todos/1`,
      headers: {
      Authorization: 'Bearer 123'
      }
      }


      And make the request like so:



      getTodos = (PARAMS) => {
      return doRequest(PARAMS).then((result) => {
      if (result.errors) { throw result }
      return {
      'statusCode': 200,
      'body': JSON.stringify({ message: result.title }),
      }
      }).catch((error) => ({
      'statusCode': error.statusCode,
      'body': JSON.stringify({ message: error.message }),
      }
      ))
      }


      Now my question is how i can test this bit of code properly. I have looked on how to tackle this with the Nock.js libary but i don't have a good understanding on where to start.
      If anyone can point me in the right direction on how to start with writing some tests for this bit of code i will be thankfull.







      javascript node.js unit-testing testing mocking






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 15:42









      MitchMitch

      827




      827
























          1 Answer
          1






          active

          oldest

          votes


















          1














          In general, you would want to black box your HTTP handling, so that as few modules in your application need to care about the details of HTTP as possible.



          In the source folder, you'd have one module (e.g. commonhttp.js). You want this to export your HTTP functions, and other modules in your application use them like this:



          const commonhttp = require('./commonhttp');
          commonhttp.doRequest( ... ).then( ... );


          Other modules, like todos.js, and various other modules, will export their own functions using that module, for example:



          const commonhttp = require('./commonhttp');

          const todos = {
          getTodos( ... ) {
          return commonhttp.doRequest( ... );
          },

          createTodo( ... ) {
          return commonhttp.doRequest( ... );
          },

          // etc.
          };

          module.exports = todos;


          For your unit tests, when you test the todos.js module, you want to mock any calls to the commonhttp module; you can use simple mocha + Sinon for this, and spy on the doRequest method. Basically all you're testing is "when I call getTodos, I expect it to make a call to doRequest with these arguments". You'd follow this pattern for all the modules in your application that uses doRequest.



          You also, of course, want to test the commonhttp module -- that spec is where Nock might come in handy. It's not strictly necessary, you can also "block-box" the http module, but you have to set up a lot of complicated spies to mimic the behavior of http; instead, writing a spec (using Nock) that says "ok, I call doRequest with these params, that should have made this HTTP call" does make sense.






          share|improve this answer
























          • Thanks for your explaination. Now i find it much easier to wrap my mind around it :)

            – Mitch
            Jan 3 at 14:10











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54009161%2fnode-js-how-to-test-https-requests-with-promise%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          In general, you would want to black box your HTTP handling, so that as few modules in your application need to care about the details of HTTP as possible.



          In the source folder, you'd have one module (e.g. commonhttp.js). You want this to export your HTTP functions, and other modules in your application use them like this:



          const commonhttp = require('./commonhttp');
          commonhttp.doRequest( ... ).then( ... );


          Other modules, like todos.js, and various other modules, will export their own functions using that module, for example:



          const commonhttp = require('./commonhttp');

          const todos = {
          getTodos( ... ) {
          return commonhttp.doRequest( ... );
          },

          createTodo( ... ) {
          return commonhttp.doRequest( ... );
          },

          // etc.
          };

          module.exports = todos;


          For your unit tests, when you test the todos.js module, you want to mock any calls to the commonhttp module; you can use simple mocha + Sinon for this, and spy on the doRequest method. Basically all you're testing is "when I call getTodos, I expect it to make a call to doRequest with these arguments". You'd follow this pattern for all the modules in your application that uses doRequest.



          You also, of course, want to test the commonhttp module -- that spec is where Nock might come in handy. It's not strictly necessary, you can also "block-box" the http module, but you have to set up a lot of complicated spies to mimic the behavior of http; instead, writing a spec (using Nock) that says "ok, I call doRequest with these params, that should have made this HTTP call" does make sense.






          share|improve this answer
























          • Thanks for your explaination. Now i find it much easier to wrap my mind around it :)

            – Mitch
            Jan 3 at 14:10
















          1














          In general, you would want to black box your HTTP handling, so that as few modules in your application need to care about the details of HTTP as possible.



          In the source folder, you'd have one module (e.g. commonhttp.js). You want this to export your HTTP functions, and other modules in your application use them like this:



          const commonhttp = require('./commonhttp');
          commonhttp.doRequest( ... ).then( ... );


          Other modules, like todos.js, and various other modules, will export their own functions using that module, for example:



          const commonhttp = require('./commonhttp');

          const todos = {
          getTodos( ... ) {
          return commonhttp.doRequest( ... );
          },

          createTodo( ... ) {
          return commonhttp.doRequest( ... );
          },

          // etc.
          };

          module.exports = todos;


          For your unit tests, when you test the todos.js module, you want to mock any calls to the commonhttp module; you can use simple mocha + Sinon for this, and spy on the doRequest method. Basically all you're testing is "when I call getTodos, I expect it to make a call to doRequest with these arguments". You'd follow this pattern for all the modules in your application that uses doRequest.



          You also, of course, want to test the commonhttp module -- that spec is where Nock might come in handy. It's not strictly necessary, you can also "block-box" the http module, but you have to set up a lot of complicated spies to mimic the behavior of http; instead, writing a spec (using Nock) that says "ok, I call doRequest with these params, that should have made this HTTP call" does make sense.






          share|improve this answer
























          • Thanks for your explaination. Now i find it much easier to wrap my mind around it :)

            – Mitch
            Jan 3 at 14:10














          1












          1








          1







          In general, you would want to black box your HTTP handling, so that as few modules in your application need to care about the details of HTTP as possible.



          In the source folder, you'd have one module (e.g. commonhttp.js). You want this to export your HTTP functions, and other modules in your application use them like this:



          const commonhttp = require('./commonhttp');
          commonhttp.doRequest( ... ).then( ... );


          Other modules, like todos.js, and various other modules, will export their own functions using that module, for example:



          const commonhttp = require('./commonhttp');

          const todos = {
          getTodos( ... ) {
          return commonhttp.doRequest( ... );
          },

          createTodo( ... ) {
          return commonhttp.doRequest( ... );
          },

          // etc.
          };

          module.exports = todos;


          For your unit tests, when you test the todos.js module, you want to mock any calls to the commonhttp module; you can use simple mocha + Sinon for this, and spy on the doRequest method. Basically all you're testing is "when I call getTodos, I expect it to make a call to doRequest with these arguments". You'd follow this pattern for all the modules in your application that uses doRequest.



          You also, of course, want to test the commonhttp module -- that spec is where Nock might come in handy. It's not strictly necessary, you can also "block-box" the http module, but you have to set up a lot of complicated spies to mimic the behavior of http; instead, writing a spec (using Nock) that says "ok, I call doRequest with these params, that should have made this HTTP call" does make sense.






          share|improve this answer













          In general, you would want to black box your HTTP handling, so that as few modules in your application need to care about the details of HTTP as possible.



          In the source folder, you'd have one module (e.g. commonhttp.js). You want this to export your HTTP functions, and other modules in your application use them like this:



          const commonhttp = require('./commonhttp');
          commonhttp.doRequest( ... ).then( ... );


          Other modules, like todos.js, and various other modules, will export their own functions using that module, for example:



          const commonhttp = require('./commonhttp');

          const todos = {
          getTodos( ... ) {
          return commonhttp.doRequest( ... );
          },

          createTodo( ... ) {
          return commonhttp.doRequest( ... );
          },

          // etc.
          };

          module.exports = todos;


          For your unit tests, when you test the todos.js module, you want to mock any calls to the commonhttp module; you can use simple mocha + Sinon for this, and spy on the doRequest method. Basically all you're testing is "when I call getTodos, I expect it to make a call to doRequest with these arguments". You'd follow this pattern for all the modules in your application that uses doRequest.



          You also, of course, want to test the commonhttp module -- that spec is where Nock might come in handy. It's not strictly necessary, you can also "block-box" the http module, but you have to set up a lot of complicated spies to mimic the behavior of http; instead, writing a spec (using Nock) that says "ok, I call doRequest with these params, that should have made this HTTP call" does make sense.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 2 at 16:10









          Elliot NelsonElliot Nelson

          8,86731936




          8,86731936













          • Thanks for your explaination. Now i find it much easier to wrap my mind around it :)

            – Mitch
            Jan 3 at 14:10



















          • Thanks for your explaination. Now i find it much easier to wrap my mind around it :)

            – Mitch
            Jan 3 at 14:10

















          Thanks for your explaination. Now i find it much easier to wrap my mind around it :)

          – Mitch
          Jan 3 at 14:10





          Thanks for your explaination. Now i find it much easier to wrap my mind around it :)

          – Mitch
          Jan 3 at 14:10




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54009161%2fnode-js-how-to-test-https-requests-with-promise%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Mossoró

          Error while reading .h5 file using the rhdf5 package in R

          Pushsharp Apns notification error: 'InvalidToken'