<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>http &amp;mdash; Simple Engineering</title>
    <link>https://getsimple.works/tag:http</link>
    <description></description>
    <pubDate>Mon, 20 Apr 2026 15:20:31 +0000</pubDate>
    <item>
      <title>How to Mock HTTP Request and Response </title>
      <link>https://getsimple.works/how-to-mock-http-request-and-response?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[The depth of an HTTP request or response mock brings a level of complexity to the whole system. In this article, we revisit some techniques used to mock HTTP request/response when used in the same test case. &#xA;&#xA;In this article we will talk about: &#xA;&#xA;Mocking Request Objects &#xA;Mocking Response Objects &#xA;Mocking Request and Response object in the same test case. &#xA;When does it make sense to mock both Request and Response. &#xA;&#xA;  Even though this blog post was designed to offer complementary materials to those who bought my Testing nodejs Applications book, the content can help any software developer to tuneup working environment. You use this link to buy the book.  Testing nodejs Applications Book Cover&#xA;&#xA;Show me the code&#xA;&#xA;module.exports.getUsers = function getUsers(req, res, next){&#xA;  UserModel.find(req.params, (error, users){&#xA;    if(error) return next(error, null);&#xA;    return res.status(200).json(users);&#xA;  });&#xA;}&#xA;Example: in controller/get-users.js&#xA;&#xA;What can possibly go wrong?&#xA;&#xA;When trying to figure out how to approach mocking request and response objects, the following points may be a challenge:&#xA;&#xA;Stubbing the right request/response methods&#xA;Mock output that can be consumed by the other callers&#xA;Stubbing request/response handlers in the same test case&#xA;Strategic mocking that can make a live server obsolete&#xA;&#xA;How to mock Request/Response Objects the easy way&#xA;&#xA;Testing an expressjs middleware provides a good use case where mocking a request and response in the same test case makes sense. &#xA;&#xA;Key objectives are:&#xA;&#xA;Spying if certain calls have been called&#xA;Make sure the requests don&#39;t leave the local machine. &#xA;&#xA;var sinon = require(&#39;sinon&#39;),&#xA;    chai = require(&#39;chai&#39;),&#xA;    expect = chai.expect,&#xA;    getUsers = require(&#39;./controller&#39;).getUsers;&#xA;&#xA;describe(&#34;getUsers()&#34;, function() {&#xA;  it(&#34;should guarantee a response&#34;, function() {&#xA;    var req  = {}, &#xA;      res  = { send: sinon.spy()}, &#xA;      next = sinon.spy();&#xA;    getUsers(req, res, next);&#xA;    expect(res.send.calledOnce).to.equal(true);&#xA;    res.send.restore(); &#xA;  });     &#xA;});&#xA;&#xA;  code excerpt adapted from - Unit Testing Controllers the Easy Way in Express 4&#xA;&#xA;Particular Case: How to mock a response that uses a streaming, or other hard to mock interfaces. Keyword: let the flow intact, but fake read/write data instead.  &#xA;&#xA;Mocking request&#xA;&#xA;Request object provided by node-mocks-http is pretty similar to the request provided by the native http found in nodejs library&#xA;&#xA;var request;&#xA;//When method = GET|DELETE&#xA;request = httpMock.createRequest({method: method, url: url});&#xA;&#xA;//When method = PUT|POST&#xA;var request = httpMock.createRequest({method, url, body: body})&#xA;&#xA;Mocking Response&#xA;&#xA;//initialization(or beforeEach)&#xA;var response = httpMock.createResponse({&#xA;    eventEmitter: require(&#39;events&#39;).EventEmitter&#xA;});&#xA;&#xA;//Usage: somewhere in tests&#xA;let next = sinon.spy();&#xA;getUsers(request, response, next);&#xA;response.on(&#39;end|data|error&#39;, function(error){&#xA;  //write tests in this close.&#xA;});&#xA;&#xA;Using node-mocks-http is in the gray area of integration testing. However, this technique can be verifiable in use cases where the first strategy falls short. &#xA;&#xA;  There is more on integration testing mocking strategy: How to Mock HTTP Request and Response ~ Integration testing use case&#xA;&#xA;Conclusion&#xA;&#xA;In this article, we revisited strategies to mock HTTP Request and Response methods in the same test case, while using mock data to emulate interaction with remote systems. We also re-iterated the difference between stubbing and mocking, and how spies(fake) fall into the testing big picture. There are additional complimentary materials in the &#34;Testing nodejs applications&#34; book on this very same subject.&#xA;&#xA;References&#xA;&#xA;Testing nodejs Applications book&#xA;Stubbing HTTP Requests&#xA;Getting started with nodejs and mocha ~ SemaphoreCI Community Tutorials&#xA;A TDD Approach to Building a Todo API Using nodejs and mongodb ~ SemaphoreCI Community Tutorials&#xA;expressjs Request/Response  mocking utility ~ mock-express-request&#xA;HTTP Response assertions utility ~ chai-http&#xA;&#xA;#snippets #http #request #response #mocking #stubbing]]&gt;</description>
      <content:encoded><![CDATA[<p>The depth of an HTTP request or response mock brings a level of complexity to the whole system. In this article, we revisit some techniques used to mock HTTP request/response when used in the same test case.</p>

<p><strong><em>In this article we will talk about:</em></strong></p>
<ul><li>Mocking Request Objects</li>
<li>Mocking Response Objects</li>
<li>Mocking Request and Response object in the same test case.</li>
<li>When does it make sense to mock both Request and Response.</li></ul>

<blockquote><p>Even though this blog post was designed to offer complementary materials to those who bought my <strong><em><a href="https://bit.ly/2ZFJytb">Testing <code>nodejs</code> Applications book</a></em></strong>, the content can help any software developer to tuneup working environment. <strong><em><a href="https://bit.ly/2ZFJytb">You use this link to buy the book</a></em></strong>.  <a href="https://bit.ly/2ZFJytb"><img src="https://snap.as/a/42OS2vs.png" alt="Testing nodejs Applications Book Cover"/></a></p></blockquote>

<h2 id="show-me-the-code" id="show-me-the-code">Show me the code</h2>

<pre><code class="language-JavaScript">module.exports.getUsers = function getUsers(req, res, next){
  UserModel.find(req.params, (error, users){
    if(error) return next(error, null);
    return res.status(200).json(users);
  });
}
</code></pre>

<p><em><em>Example</em>: in <code>controller/get-users.js</code></em></p>

<h2 id="what-can-possibly-go-wrong" id="what-can-possibly-go-wrong">What can possibly go wrong?</h2>

<p>When trying to figure out how to approach mocking request and response objects, the following points may be a challenge:</p>
<ul><li>Stubbing the right request/response methods</li>
<li>Mock output that can be consumed by the other callers</li>
<li>Stubbing request/response handlers in the same test case</li>
<li>Strategic mocking that can make a live server obsolete</li></ul>

<h2 id="how-to-mock-request-response-objects-the-easy-way" id="how-to-mock-request-response-objects-the-easy-way">How to mock Request/Response Objects the easy way</h2>

<p>Testing an <code>expressjs</code> middleware provides a good use case where mocking a request and response in the same test case makes sense.</p>

<p>Key objectives are:</p>
<ul><li>Spying if certain calls have been called</li>
<li>Make sure the requests don&#39;t leave the local machine.</li></ul>

<pre><code class="language-JavaScript">var sinon = require(&#39;sinon&#39;),
    chai = require(&#39;chai&#39;),
    expect = chai.expect,
    getUsers = require(&#39;./controller&#39;).getUsers;

describe(&#34;getUsers()&#34;, function() {
  it(&#34;should guarantee a response&#34;, function() {
    var req  = {}, 
      res  = { send: sinon.spy()}, 
      next = sinon.spy();
    getUsers(req, res, next);
    expect(res.send.calledOnce).to.equal(true);
    res.send.restore(); 
  });     
});
</code></pre>

<blockquote><p>code excerpt adapted from – <a href="https://www.designsuperbuild.com/blog/unit_testing_controllers_in_express/">Unit Testing Controllers the Easy Way in Express 4</a></p></blockquote>

<p><strong><em>Particular Case</em></strong>: How to mock a response that uses a streaming, or other hard to mock interfaces. Keyword: let the flow intact, but fake read/write data instead.</p>

<h2 id="mocking-request" id="mocking-request">Mocking request</h2>

<p>Request object provided by <code>node-mocks-http</code> is pretty similar to the request provided by the native <code>http</code> found in <code>nodejs</code> library</p>

<pre><code class="language-JavaScript">var request;
//When method = GET|DELETE
request = httpMock.createRequest({method: method, url: url});

//When method = PUT|POST
var request = httpMock.createRequest({method, url, body: body})
</code></pre>

<h2 id="mocking-response" id="mocking-response">Mocking Response</h2>

<pre><code class="language-JavaScript">//initialization(or beforeEach)
var response = httpMock.createResponse({
    eventEmitter: require(&#39;events&#39;).EventEmitter
});

//Usage: somewhere in tests
let next = sinon.spy();
getUsers(request, response, next);
response.on(&#39;end|data|error&#39;, function(error){
  //write tests in this close.
});
</code></pre>

<p>Using <code>node-mocks-http</code> is in the gray area of integration testing. However, this technique can be verifiable in use cases where the first strategy falls short.</p>

<blockquote><p>There is more on integration testing mocking strategy: <a href="./how-to-mock-http-request-response-integration-testing-use-case">How to Mock HTTP Request and Response ~ Integration testing use case</a></p></blockquote>

<h2 id="conclusion" id="conclusion">Conclusion</h2>

<p>In this article, we revisited strategies to mock HTTP Request and Response methods in the same test case, while using mock data to emulate interaction with remote systems. We also re-iterated the difference between stubbing and mocking, and how spies(fake) fall into the testing big picture. There are additional complimentary materials in the <strong>“Testing <code>nodejs</code> applications”</strong> book on this very same subject.</p>

<h2 id="references" id="references">References</h2>
<ul><li><a href="https://bit.ly/2ZFJytb">Testing <code>nodejs</code> Applications book</a></li>
<li><a href="https://mherman.org/blog/2017/11/06/stubbing-http-requests-with-sinon/#.WpL2UBMbPUI">Stubbing HTTP Requests</a></li>
<li>Getting started with <code>nodejs</code> and <code>mocha</code> ~ <a href="https://semaphoreci.com/community/tutorials/getting-started-with-node-js-and-mocha">SemaphoreCI Community Tutorials</a></li>
<li>A TDD Approach to Building a Todo API Using <code>nodejs</code> and <code>mongodb</code> ~ <a href="https://semaphoreci.com/community/tutorials/a-tdd-approach-to-building-a-todo-api-using-node-js-and-mongodb">SemaphoreCI Community Tutorials</a></li>
<li><code>expressjs</code> Request/Response  mocking utility ~ <a href="https://www.npmjs.com/package/mock-express-request">mock-express-request</a></li>
<li>HTTP Response assertions utility ~ <a href="https://chaijs.com/plugins/chai-http">chai-http</a></li></ul>

<p><a href="https://getsimple.works/tag:snippets" class="hashtag"><span>#</span><span class="p-category">snippets</span></a> <a href="https://getsimple.works/tag:http" class="hashtag"><span>#</span><span class="p-category">http</span></a> <a href="https://getsimple.works/tag:request" class="hashtag"><span>#</span><span class="p-category">request</span></a> <a href="https://getsimple.works/tag:response" class="hashtag"><span>#</span><span class="p-category">response</span></a> <a href="https://getsimple.works/tag:mocking" class="hashtag"><span>#</span><span class="p-category">mocking</span></a> <a href="https://getsimple.works/tag:stubbing" class="hashtag"><span>#</span><span class="p-category">stubbing</span></a></p>
]]></content:encoded>
      <guid>https://getsimple.works/how-to-mock-http-request-and-response</guid>
      <pubDate>Wed, 16 Jun 2021 22:24:16 +0000</pubDate>
    </item>
    <item>
      <title>How to Mock HTTP Request and Response ~ Integration testing use case.</title>
      <link>https://getsimple.works/how-to-mock-http-request-and-response-integration-testing-use-case?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[Mocking HTTP requests, for that matter responses, is essential in most unit test scenarios. Depending on the depth we want the mock to kick in, this task can become quite a feat on its own. In this article, we revisit some techniques that can make our life easy when mocking requests in integration testing scenarios. &#xA;&#xA;  This article is a followup to How to Mock HTTP Request and Response&#xA;&#xA;In this article we will talk about: &#xA;&#xA;Stubbing HTTP Request Objects &#xA;Mocking Request and Response object in the same test case. &#xA;When does it make sense to mock both Request and Response. &#xA;&#xA;  Even though this blog post was designed to offer complementary materials to those who bought my Testing nodejs Applications book, the content can help any software developer to tuneup working environment. You use this link to buy the book.  Testing nodejs Applications Book Cover&#xA;&#xA;Show me the code&#xA;&#xA;//&#xA;var User = require(&#39;./models&#39;).User; &#xA;module.exports = function getProfile(req, res, next){&#xA;  User.findById(req.params.id, function(error, user){&#xA;    if(error) return next(error);&#xA;    return res.status(200).json(user);&#xA;  });&#xA;};&#xA;&#xA;//Router that Authentication Middleware&#xA;var router = require(&#39;express&#39;).Router();&#xA;var authenticated = require(&#39;./middleware/authenticated&#39;);&#xA;var getUsers = require(&#39;./users/get-user&#39;);&#xA;router.get(&#39;/users/:id&#39;, authenticated, getUser);&#xA;module.exports = router;&#xA;&#xA;Example:&#xA;&#xA;What can possibly go wrong?&#xA;&#xA;Some challenges associated with stubbing HTTP requests:&#xA;&#xA;How deep a stub should go&#xA;&#xA;Show me the tests &#xA;&#xA;The next section has the following traits backed in:&#xA;&#xA;When to use: Testing all routes at once &#xA;When to use: Asserting on nature of the response output&#xA;When not to use: When running unit testing&#xA;When to use: When running integration tests&#xA; &#xA;// Add promise support if this does not exist natively.&#xA;if (!global.Promise) {&#xA;    global.Promise = require(&#39;q&#39;);//or any other promise library &#xA;}&#xA;&#xA;var chai = require(&#39;chai&#39;),&#xA;  chaiHttp = require(&#39;chai-http&#39;),&#xA;  chai.use(chaiHttp), //registering the plugin.&#xA;  //use this line to retain cookies instead &#xA;  agent = chai.request.agent(app),&#xA;  //agent.post()|agent.get()|agent.del()|agent.put &#xA;  app = require(&#39;express&#39;).Router(),&#xA;  //mounting app to routes to be tested&#xA;  require(&#39;./lib/routes&#39;)(app);&#xA;&#xA;//initialization of app can be express or other HTTP compatible server.&#xA;it(&#39;works&#39;, function(done){&#xA;    chai.request(app)&#xA;    .put(&#39;/user/me&#39;)//.post|get|delete&#xA;    .send({ password: &#39;123&#39;, confirm: &#39;123&#39; })&#xA;    .end(function (err, res) {&#xA;        expect(err).to.be.null;&#xA;        expect(res).to.have.status(200);&#xA;        //more possible assertion &#xA;        expect(res).to.have.status(200);&#xA;        expect(req).to.have.header(&#39;x-api-key&#39;);&#xA;        expect(req).to.have.headers;//Assert that a Response or Request object has headers.&#xA;        expect(req).to.be.json;//.html|.text &#xA;        expect(res).to.redirect;//.to.not.redirect&#xA;        expect(req).to.have.param(&#39;orderby&#39;);//test sent parameters&#xA;        expect(req).to.have.param(&#39;orderby&#39;, &#39;date&#39;);//test sent parameters values &#xA;        expect(req).to.have.cookie(&#39;sessionid&#39;);//test cookie parameters&#xA;    });&#xA;});&#xA;&#xA;//keeping port open &#xA;var requester = chai.request(app).keepOpen();&#xA;it(&#39;works - parallel requests&#39;, function(){&#xA;    Promise.all([requester.get(&#39;/a&#39;), requester.get(&#39;/b&#39;)])&#xA;    .then(responses =  { /*do - more assertions here /})&#xA;    .then(() =  requester.close());&#xA;});&#xA;&#xA;  This strategy has not been tested on routes that read/write streams. &#xA;&#xA;To the question: When does it make sense to mock both Request and Response_, the answer is it depends. In the event where were are interested in replicating interactions with a third party system via Requests/Responses, then it makes sense to mock request/responses.  &#xA;&#xA;Conclusion&#xA;&#xA;In this article, we established the difference between Mocking versus Stubbing HTTP requests. &#xA;&#xA;We also established the cost associated with HTTP request every time a test is executed. &#xA;&#xA;With this knowledge, we reviewed ways to reduce costs by strategically stubbing HTTP read/write operations to make tests fail fast, without losing test effectiveness. There are additional complimentary materials in the &#34;Testing nodejs applications&#34; book.  &#xA;&#xA;References&#xA;&#xA;Testing nodejs Applications book&#xA;Stubbing HTTP Requests&#xA;How to add global variables used by all tests in Javascript? StackOverflow Question &#xA;Problem resetting global object. Bug#1 about adding should on global object&#xA;Problem resetting global object. Bug#2 How to make expect/should/assert be global in test files and be able to pass eslint&#xA;expressjs Request/Response  mocking utility ~ mock-express-request&#xA;HTTP Response assertions utility ~ chai-http&#xA;&#xA;#snippets #http #request #response #mocking #stubbing]]&gt;</description>
      <content:encoded><![CDATA[<p>Mocking HTTP requests, for that matter responses, is essential in most unit test scenarios. Depending on the depth we want the mock to kick in, this task can become quite a feat on its own. In this article, we revisit some techniques that can make our life easy when mocking requests in integration testing scenarios.</p>

<blockquote><p>This article is a followup to <a href="./how-to-mock-http-request-and-response">How to Mock HTTP Request and Response</a></p></blockquote>

<p><strong><em>In this article we will talk about:</em></strong></p>
<ul><li>Stubbing HTTP Request Objects</li>
<li>Mocking Request and Response object in the same test case.</li>
<li>When does it make sense to mock both Request and Response.</li></ul>

<blockquote><p>Even though this blog post was designed to offer complementary materials to those who bought my <strong><em><a href="https://bit.ly/2ZFJytb">Testing <code>nodejs</code> Applications book</a></em></strong>, the content can help any software developer to tuneup working environment. <strong><em><a href="https://bit.ly/2ZFJytb">You use this link to buy the book</a></em></strong>.  <a href="https://bit.ly/2ZFJytb"><img src="https://snap.as/a/42OS2vs.png" alt="Testing nodejs Applications Book Cover"/></a></p></blockquote>

<h2 id="show-me-the-code" id="show-me-the-code">Show me the code</h2>

<pre><code class="language-JavaScript">//
var User = require(&#39;./models&#39;).User; 
module.exports = function getProfile(req, res, next){
  User.findById(req.params.id, function(error, user){
    if(error) return next(error);
    return res.status(200).json(user);
  });
};

//Router that Authentication Middleware
var router = require(&#39;express&#39;).Router();
var authenticated = require(&#39;./middleware/authenticated&#39;);
var getUsers = require(&#39;./users/get-user&#39;);
router.get(&#39;/users/:id&#39;, authenticated, getUser);
module.exports = router;

</code></pre>

<p><em><em>Example</em>:</em></p>

<h2 id="what-can-possibly-go-wrong" id="what-can-possibly-go-wrong">What can possibly go wrong?</h2>

<p>Some challenges associated with stubbing HTTP requests:</p>
<ul><li>How deep a stub should go</li></ul>

<h2 id="show-me-the-tests" id="show-me-the-tests">Show me the tests</h2>

<p>The next section has the following traits backed in:</p>
<ul><li>When to use: Testing all routes at once</li>
<li>When to use: Asserting on nature of the response output</li>
<li>When not to use: When running unit testing</li>
<li>When to use: When running integration tests</li></ul>

<pre><code class="language-JavaScript">// Add promise support if this does not exist natively.
if (!global.Promise) {
    global.Promise = require(&#39;q&#39;);//or any other promise library 
}

var chai = require(&#39;chai&#39;),
  chaiHttp = require(&#39;chai-http&#39;),
  chai.use(chaiHttp), //registering the plugin.
  //use this line to retain cookies instead 
  agent = chai.request.agent(app),
  //agent.post()|agent.get()|agent.del()|agent.put 
  app = require(&#39;express&#39;).Router(),
  //mounting app to routes to be tested
  require(&#39;./lib/routes&#39;)(app);

//initialization of app can be express or other HTTP compatible server.
it(&#39;works&#39;, function(done){
    chai.request(app)
    .put(&#39;/user/me&#39;)//.post|get|delete
    .send({ password: &#39;123&#39;, confirm: &#39;123&#39; })
    .end(function (err, res) {
        expect(err).to.be.null;
        expect(res).to.have.status(200);
        //more possible assertion 
        expect(res).to.have.status(200);
        expect(req).to.have.header(&#39;x-api-key&#39;);
        expect(req).to.have.headers;//Assert that a Response or Request object has headers.
        expect(req).to.be.json;//.html|.text 
        expect(res).to.redirect;//.to.not.redirect
        expect(req).to.have.param(&#39;orderby&#39;);//test sent parameters
        expect(req).to.have.param(&#39;orderby&#39;, &#39;date&#39;);//test sent parameters values 
        expect(req).to.have.cookie(&#39;session_id&#39;);//test cookie parameters
    });
});

//keeping port open 
var requester = chai.request(app).keepOpen();
it(&#39;works - parallel requests&#39;, function(){
    Promise.all([requester.get(&#39;/a&#39;), requester.get(&#39;/b&#39;)])
    .then(responses =&gt; { /**do - more assertions here */})
    .then(() =&gt; requester.close());
});

</code></pre>

<blockquote><p>This strategy has not been tested on routes that read/write streams.</p></blockquote>

<p>To the question: <em>When does it make sense to mock both Request and Response</em>, the answer is it depends. In the event where were are interested in replicating interactions with a third party system via Requests/Responses, then it makes sense to mock request/responses.</p>

<h2 id="conclusion" id="conclusion">Conclusion</h2>

<p>In this article, we established the difference between Mocking versus Stubbing HTTP requests.</p>

<p>We also established the cost associated with HTTP request every time a test is executed.</p>

<p>With this knowledge, we reviewed ways to reduce costs by strategically stubbing HTTP read/write operations to make tests fail fast, without losing test effectiveness. There are additional complimentary materials in the <strong>“Testing <code>nodejs</code> applications”</strong> book.</p>

<h2 id="references" id="references">References</h2>
<ul><li><a href="https://bit.ly/2ZFJytb">Testing <code>nodejs</code> Applications book</a></li>
<li><a href="https://mherman.org/blog/2017/11/06/stubbing-http-requests-with-sinon/#.WpL2UBMbPUI">Stubbing HTTP Requests</a></li>
<li>How to add global variables used by all tests in Javascript? <a href="https://stackoverflow.com/q/28449902/132610">StackOverflow Question</a></li>
<li>Problem resetting global object. <a href="https://github.com/chaijs/chai/issues/86">Bug#1 about adding should on global object</a></li>
<li>Problem resetting global object. <a href="https://github.com/chaijs/chai/issues/891">Bug#2 How to make expect/should/assert be global in test files and be able to pass <code>eslint</code></a></li>
<li><code>expressjs</code> Request/Response  mocking utility ~ <a href="https://www.npmjs.com/package/mock-express-request">mock-express-request</a></li>
<li>HTTP Response assertions utility ~ <a href="https://chaijs.com/plugins/chai-http">chai-http</a></li></ul>

<p><a href="https://getsimple.works/tag:snippets" class="hashtag"><span>#</span><span class="p-category">snippets</span></a> <a href="https://getsimple.works/tag:http" class="hashtag"><span>#</span><span class="p-category">http</span></a> <a href="https://getsimple.works/tag:request" class="hashtag"><span>#</span><span class="p-category">request</span></a> <a href="https://getsimple.works/tag:response" class="hashtag"><span>#</span><span class="p-category">response</span></a> <a href="https://getsimple.works/tag:mocking" class="hashtag"><span>#</span><span class="p-category">mocking</span></a> <a href="https://getsimple.works/tag:stubbing" class="hashtag"><span>#</span><span class="p-category">stubbing</span></a></p>
]]></content:encoded>
      <guid>https://getsimple.works/how-to-mock-http-request-and-response-integration-testing-use-case</guid>
      <pubDate>Wed, 16 Jun 2021 22:22:05 +0000</pubDate>
    </item>
  </channel>
</rss>