title: Mocking Http Post Request using Jest in NodeJs
body: <p>I have an external POST API built using native https.request using Node Js inside Azure Function and everything works fine. Now I am trying to build Unit Test cases and got struck at mocking Request method.</p>
  <p>The callback response has 'on' function which needs to be mocked based on value either 'data' or 'end'.</p>
  <p>I get this error <strong>TypeError: res.on is not a function</strong></p>
  <p>Below is the Code. Any suggestions !</p>
  <p>index.js</p>
  <pre><code>'use strict';
  const https = require('https')
  const fs = require('fs')
  const path = require('path')
  
  module.exports = function(context, postData) {
      //Accessing Certificate and Passing along with Request Options for SSL Handshake
      var ca_path = path.join(__dirname, 'my_cert.cer');
      https.globalAgent.options.ca = fs.readFileSync(ca_path).toString()
          .split(/-----END CERTIFICATE-----\n?/)
          // may include an extra empty string at the end
          .filter(function(cert) { return cert !== ''; })
          // effectively split after delimiter by adding it back
          .map(function(cert) { return cert + '-----END CERTIFICATE-----\n'; });
  
      let auth = 'Basic ' + Buffer.from(process.env.username + ':' + process.env.pwd).toString('base64');
  
      let post_option = {
          host: process.env.host,
          path: process.env.path,
          method: 'POST',
          port: process.env.port,
          headers: {
              'Content-Type': 'application/json',
              'Authorization': auth,
              'X-Correlation-ID': JSON.parse(postData).correlationId
          }
      };
  
      return new Promise(function(resolve, reject) {
          var req = https.request(post_option, function(res) {
              // accumulate data
              var body = [];
              res.on('data', function(chunk) { //here is the type error
                  body.push(chunk);
              });
              // resolve on end
              res.on('end', function() {
                  context.log(&quot;API status: &quot; + res.statusCode);
                  if (res.statusCode == 200) {
                      try {
                          body = JSON.parse(Buffer.concat(body).toString());
                          context.log(&quot;API Success: &quot;);
                      } catch (err) {
                          reject(err);
                      }
                      resolve(body);
                  } else if (res.statusCode == 401) {
                      let errJson = {};
                      context.log(&quot;API authentication error...&quot;);
                      let err = new Error();
                      errJson[&quot;errorCode&quot;] = res.statusCode;
                      errJson[&quot;errorMessage&quot;] = res.statusMessage;
                      errJson[&quot;errorDescription&quot;] = res.statusMessage;
                      err = errJson;
                      return reject(err);
                  } else {
                      body = JSON.parse(Buffer.concat(body).toString());
                      context.log(&quot;API error...&quot;, body);
                      let err = new Error();
  
                      if (body.error != null &amp;&amp; body.error != undefined) {
                          err = body.error;
                      } else {
                          let errJson = {};
                          errJson[&quot;errorCode&quot;] = res.statusCode;
                          errJson[&quot;errorMessage&quot;] = res.statusMessage;
                          errJson[&quot;errorDescription&quot;] = res.statusMessage;
                          err = errJson;
                      }
                      return reject(err);
                  }
              });
          });
          // reject on request error
          req.on('error', function(err) {
              context.log(&quot;API Generic error...&quot;, err);
              let err = new Error();
              let errJson = {};
              if (err.message &amp;&amp; err.message.indexOf(&quot;ENOTFOUND&quot;) &gt;= 0)
                  errJson[&quot;errorCode&quot;] = 404;
              else
                  errJson[&quot;errorCode&quot;] = 500;
              errJson[&quot;errorMessage&quot;] = err.message;
              errJson[&quot;errorDescription&quot;] = err.message;
              err = errJson;
              reject(err);
          });
          if (postData) {
              req.write(postData);
          }
          req.end();
      });
  }
  </code></pre>
  <p>index.test.js</p>
  <pre><code> var https = require('https');
      jest.mock('https', () =&gt; ({
      ...jest.requireActual('https'), // import and retain the original functionalities
      request: (post_option, cb) =&gt; cb('res')({
           on: jest.fn()
      }),
      on: jest.fn(),
      write: jest.fn(),
      end: jest.fn()
  }));
  
  
   /*
  jest.mock('https', () =&gt; ({
  ...jest.requireActual('https'), // import and retain the original functionalities
  request: (post_option, cb) =&gt; cb('res')({
      on: (data, cb) =&gt; cb('data')
  }),
  on: jest.fn(),
  write: jest.fn(),
  end: jest.fn()
  }));
  */
  
  /*    jest.mock('https', () =&gt; ({
        ...jest.requireActual('https'), // import and retain the original functionalities
        request: (post_option, cb) =&gt; cb(jest.fn(() =&gt; ({
          on: jest.fn()
        }))),
        on: jest.fn(),
        write: jest.fn(),
        end: jest.fn()
        })); 
  */
  
  /*  jest.mock('https', () =&gt; ({
      ...jest.requireActual('https'), // import and retain the original functionalities
      request: (post_option, cb) =&gt; cb({
       on: jest.fn()
      })
      })); 
  */
  </code></pre>
  <p>Tried different ways to create mock for 'on' function but not success.</p>