<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>http — Simple Engineering</title>
    <link>https://getsimple.works/tag:http</link>
    <description></description>
    <pubDate>Thu, 12 Nov 2026 15:00:43 +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>The depth of an HTTP request or response mock brings a level of complexity to the whole system. In this article, we revisit some techniqu...</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">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">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">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">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">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">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">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>Mocking HTTP requests, for that matter responses, is essential in most unit test scenarios. Depending on the depth we want the mock to ki...</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">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">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">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">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">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>