<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>expressjs &amp;mdash; Simple Engineering</title>
    <link>https://getsimple.works/tag:expressjs</link>
    <description></description>
    <pubDate>Wed, 15 Apr 2026 06:14:22 +0000</pubDate>
    <item>
      <title>Modularization of nodejs servers</title>
      <link>https://getsimple.works/modularization-of-nodejs-servers?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[A server requires the use of network resources, some of which perform expensive read/write operations. Testing servers introduce side effects, some of which expensive, and may cause unintended consequences when not mocked in the testing phase. To limit the chances of breaking something, testing servers have to be done in isolation. &#xA;&#xA;The question to ask at this stage, is How to get there?. This blog article will explore some of the ways to answer this question.&#xA;&#xA;The motivation for modularization is to reduce the complexity associated with large-scale expressjs applications.  In nodejs servers context, we will shift focus on making sure most of the parts are accessible for tests in isolation.&#xA;&#xA;In this article we will talk about:&#xA;&#xA;How to modularize nodejs server for reusability.     &#xA;How to modularize nodejs server for testability. &#xA;How to modularize nodejs server for composability.  &#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;nodejs application server comes in two flavors. Using native nodejs library, or adopting a server provided via a framework, in our case expressjs.&#xA;&#xA;Using expressjs framework a classic server code looks as is the following example:&#xA;&#xA;var express = require(&#39;express&#39;),&#xA;    app = express()&#xA;/* .. more routes + code for app ... /&#xA;app.get(&#39;/&#39;, function (req, res) {&#xA;  return res.send(&#39;Hello World!&#39;)&#xA;});&#xA;&#xA;app.listen(port, function () {&#xA;  console.log(&#39;Example app listening on port 3000!&#39;)&#xA;});&#xA;//source: https://expressjs.com/en/starter/hello-world.html&#xA;Example:&#xA;&#xA;As the requirement increases, this file becomes exponentially big. The most application runs on top of expressjs a popular library in nodejs world. To keep the server.js small, regardless of requirements and dependent modules, moving most of the code into modules makes a difference.  &#xA;&#xA;var http = require(&#39;http&#39;),&#xA;  hostname = &#39;localhost&#39;,&#xA;  port = process.env.PORT || 3000,&#xA;  server = http.createServer(function(req, res){&#xA;    res.statusCode = 200;&#xA;    res.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);&#xA;    res.end(&#39;Hello World\n&#39;);&#xA;  });&#xA;&#xA;//Alternatively&#xA;var express = require(&#39;express&#39;),&#xA;    app = express(),&#xA;    require(&#39;app/routes&#39;)(app),&#xA;    server = http.createServer(app);&#xA;&#xA;server.listen(port, hostname, function (){&#xA;  console.log([&#39;Server running at http://&#39;,hostname,&#39;:&#39;,port].join());&#xA;});&#xA;//source: https://nodejs.org/api/synopsis.html#synopsisexample&#xA;Example:&#xA;&#xA;What can possibly go wrong?&#xA;&#xA;When trying to figure out how to approach modularizing nodejs servers, the following points may be a challenge:&#xA;&#xA;Understanding where to start, and where to stop with server modularization&#xA;Understanding key parts that need abstraction, or how/where to inject dependencies&#xA;Making servers testable &#xA;&#xA;The following sections will explore more on making points stated above work. &#xA;&#xA;How to modularize nodejs server for reusability&#xA;&#xA;How to apply modularization technique in a server context or How to break down larger server file into a smaller granular alternative. &#xA;&#xA;The server reusability becomes an issue when it becomes clear that the server bootstrapping code either needs some refactoring or presents an opportunity to add extra test coverage. &#xA;&#xA;In order to make the server available to the third-party sandboxed testing environment, the server has to be exportable first. &#xA;&#xA;In order to be able to load and mock/stub certain areas of the server code, still the server has to be exportable. &#xA;&#xA;Like any other modularization technique we used, two steps are going to be in play. Since our case concerns multiple players, for instance, expressjs WebSocket and whatnot, we have to look at the server like an equal of those other possible servers. &#xA;&#xA;How to modularize nodejs server for testability&#xA;&#xA;Simulations of start/stop while running tests are catalysts of this exercise. &#xA;&#xA;Testability and composability are other real drives to get the server to be modular. A modular server makes it easy to load the server as we load any other object into the testing sandbox, as well as mocking any dependency we deem unnecessary or prevents us to get the job done. &#xA;&#xA;  Simulation of Start/Stop while running tests&#xA;  - How to correctly unit test express server&#xA;  - There is a better code structure organization, that make it easy to test, get coverage, etc. Testing nodejs with mocha&#xA;&#xA;The previous example shows how simpler becomes server initialization, but that comes with the additional library to install. Modularization of the above two code segments makes it possible to test the server in isolation.  &#xA;&#xA;module.exports = server;&#xA;Example: Modularization - this line makes server available in our tests ~ source_&#xA;&#xA;How to modularize nodejs server for composability&#xA;&#xA;The challenge is to expose the HTTP server, in a way redis/websocket or agenda can re-use the same server. Making the server injectable. &#xA;&#xA;The composability of the server is rather counter-intuitive. In most cases, the server will be injected into other components, for those components to mount additional server capabilities. The code sample proves this point by making the HTTP server available to a WebSocket component so that the WebSocket can be aware and mounted/attached to the same instance of the HTTP server. &#xA;&#xA;var http = require(&#39;http&#39;), &#xA;    app = require(&#39;express&#39;)(),&#xA;    server = http.createServer(app),&#xA;    sio = require(&#34;socket.io&#34;)(server);&#xA;&#xA;...&#xA;&#xA;module.exports = server;&#xA;&#xA;Conclusion&#xA;&#xA;Modularization is key in making nodejs server elegant, serve as a baseline to performance improvements and improved testability. In this article, we revisited how to achieve nodejs server modularity, with stress on testability and code reusability. There are additional complimentary materials in the &#34;Testing nodejs applications&#34; book.  &#xA;&#xA;References&#xA;&#xA;Testing nodejs Applications book&#xA;&#xA;tags: #snippets #modularization #nodejs #expressjs]]&gt;</description>
      <content:encoded><![CDATA[<p>A server requires the use of network resources, some of which perform expensive read/write operations. Testing servers introduce side effects, some of which expensive, and may cause unintended consequences when not mocked in the testing phase. To limit the chances of breaking something, testing servers have to be done in isolation.</p>

<p>The question to ask at this stage, is <em>How to get there?</em>. This blog article will explore some of the ways to answer this question.</p>

<p>The motivation for modularization is to reduce the complexity associated with large-scale <code>expressjs</code> applications.  In <code>nodejs</code> servers context, we will shift focus on making sure most of the parts are accessible for tests in isolation.</p>

<p><strong><em>In this article we will talk about:</em></strong></p>
<ul><li>How to modularize <code>nodejs</code> server for reusability.<br/></li>
<li>How to modularize <code>nodejs</code> server for testability.</li>
<li>How to modularize <code>nodejs</code> server for composability.<br/></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>

<p><code>nodejs</code> application server comes in two flavors. Using native <code>nodejs</code> library, or adopting a server provided via a framework, in our case <code>expressjs</code>.</p>

<p>Using <code>expressjs</code> framework a classic server code looks as is the following example:</p>

<pre><code class="language-JavaScript">var express = require(&#39;express&#39;),
    app = express()
/** .. more routes + code for app ... */
app.get(&#39;/&#39;, function (req, res) {
  return res.send(&#39;Hello World!&#39;)
});

app.listen(port, function () {
  console.log(&#39;Example app listening on port 3000!&#39;)
});
//source: https://expressjs.com/en/starter/hello-world.html
</code></pre>

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

<p>As the requirement increases, this file becomes exponentially big. The most application runs on top of <code>expressjs</code> a popular library in <code>nodejs</code> world. To keep the <code>server.js</code> small, regardless of requirements and dependent modules, moving most of the code into modules makes a difference.</p>

<pre><code class="language-JavaScript">var http = require(&#39;http&#39;),
  hostname = &#39;localhost&#39;,
  port = process.env.PORT || 3000,
  server = http.createServer(function(req, res){
    res.statusCode = 200;
    res.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);
    res.end(&#39;Hello World\n&#39;);
  });

//Alternatively
var express = require(&#39;express&#39;),
    app = express(),
    require(&#39;app/routes&#39;)(app),
    server = http.createServer(app);

server.listen(port, hostname, function (){
  console.log([&#39;Server running at http://&#39;,hostname,&#39;:&#39;,port].join());
});
//source: https://nodejs.org/api/synopsis.html#synopsis_example
</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>When trying to figure out how to approach modularizing <code>nodejs</code> servers, the following points may be a challenge:</p>
<ul><li>Understanding where to start, and where to stop with server modularization</li>
<li>Understanding key parts that need abstraction, or how/where to inject dependencies</li>
<li>Making servers testable</li></ul>

<p>The following sections will explore more on making points stated above work.</p>

<h2 id="how-to-modularize-nodejs-server-for-reusability" id="how-to-modularize-nodejs-server-for-reusability">How to modularize <code>nodejs</code> server for reusability</h2>

<p><em>How to apply modularization technique in a server context</em> or <em>How to break down larger server file into a smaller granular alternative</em>.</p>

<p>The server reusability becomes an issue when it becomes clear that the <em>server bootstrapping code</em> either needs some refactoring or presents an opportunity to add extra test coverage.</p>

<p>In order to make the server available to the third-party sandboxed testing environment, the server has to be exportable first.</p>

<p>In order to be able to load and mock/stub certain areas of the server code, still the server has to be exportable.</p>

<p>Like any other modularization technique we used, two steps are going to be in play. Since our case concerns multiple players, for instance, <code>expressjs</code> WebSocket and whatnot, we have to look at the server like an equal of those other possible servers.</p>

<h2 id="how-to-modularize-nodejs-server-for-testability" id="how-to-modularize-nodejs-server-for-testability">How to modularize <code>nodejs</code> server for testability</h2>

<p>Simulations of start/stop while running tests are catalysts of this exercise.</p>

<p>Testability and composability are other real drives to get the server to be modular. A modular server makes it easy to load the server as we load any other object into the testing sandbox, as well as mocking any dependency we deem unnecessary or prevents us to get the job done.</p>

<blockquote><p><strong><em>Simulation of Start/Stop while running tests</em></strong>
– <a href="https://glebbahmutov.com/blog/how-to-correctly-unit-test-express-server/">How to correctly unit test express server</a>
– There is a better code structure organization, that make it easy to test, get coverage, etc. <a href="https://brianstoner.com/blog/testing-in-nodejs-with-mocha/">Testing <code>nodejs</code> with mocha</a></p></blockquote>

<p>The previous example shows how simpler becomes server initialization, but that comes with the additional library to install. Modularization of the above two code segments makes it possible to test the server in isolation.</p>

<pre><code class="language-JavaScript">module.exports = server;
</code></pre>

<p><em><em>Example</em>: Modularization – this line makes server available in our tests ~ <a href="https://glebbahmutov.com/blog/how-to-correctly-unit-test-express-server/">source</a></em></p>

<h2 id="how-to-modularize-nodejs-server-for-composability" id="how-to-modularize-nodejs-server-for-composability">How to modularize <code>nodejs</code> server for composability</h2>

<p>The challenge is to expose the HTTP server, in a way <code>redis</code>/<code>websocket</code> or <code>agenda</code> can re-use the same server. Making the server injectable.</p>

<p>The composability of the server is rather counter-intuitive. In most cases, the server will be injected into other components, for those components to mount additional server capabilities. The code sample proves this point by making the HTTP server available to a WebSocket component so that the WebSocket can be aware and mounted/attached to the same instance of the HTTP server.</p>

<pre><code class="language-JavaScript">var http = require(&#39;http&#39;), 
    app = require(&#39;express&#39;)(),
    server = http.createServer(app),
    sio = require(&#34;socket.io&#34;)(server);

...

module.exports = server;
</code></pre>

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

<p>Modularization is key in making <code>nodejs</code> server elegant, serve as a baseline to performance improvements and improved testability. In this article, we revisited how to achieve <code>nodejs</code> server modularity, with stress on testability and code reusability. 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></ul>

<p>tags: <a href="https://getsimple.works/tag:snippets" class="hashtag"><span>#</span><span class="p-category">snippets</span></a> <a href="https://getsimple.works/tag:modularization" class="hashtag"><span>#</span><span class="p-category">modularization</span></a> <a href="https://getsimple.works/tag:nodejs" class="hashtag"><span>#</span><span class="p-category">nodejs</span></a> <a href="https://getsimple.works/tag:expressjs" class="hashtag"><span>#</span><span class="p-category">expressjs</span></a></p>
]]></content:encoded>
      <guid>https://getsimple.works/modularization-of-nodejs-servers</guid>
      <pubDate>Thu, 17 Jun 2021 05:49:15 +0000</pubDate>
    </item>
    <item>
      <title>Modularizing nodejs applications ~ Manifest routes</title>
      <link>https://getsimple.works/modularizing-nodejs-applications-manifest-routes?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[We assume most of the system components to be accessible for testability. However, that is challenging when routes are a little bit complex. To reduce the complexity that comes with working on large-scale expressjs routes, we will apply a technique known as manifest routes to make route declarations change proof, making them more stable as the rest of the application evolves.&#xA;&#xA;In this article we will talk about:&#xA;&#xA;The need to have manifest routes technique &#xA;How to apply the manifest routes as a modularization technique&#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;var express = require(&#39;express&#39;)&#xA;var app = express();&#xA;&#xA;app.get(&#39;/&#39;, function(req, res, next) {  &#xA;  res.render(&#39;index&#39;, { title: &#39;Express&#39; });&#xA;});&#xA;&#xA;/* code that initialize everything, then comes this route/&#xA;app.get(&#39;/users/:id&#39;, function(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;app.listen(port, function () {&#xA;  console.log(&#39;Example app listening on port 3000!&#39;)&#xA;});&#xA;&#xA;What can possibly go wrong?&#xA;&#xA;When trying to figure out how to approach modularization of expressjs routes with a manifest route pattern, the following points may be a challenge:&#xA;&#xA;Where to start with modularization without breaking the rest of the application&#xA;How to introduce the layered architecture, without incurring additional test burden, but making it easier to isolate tests&#xA;&#xA;The following sections will explore more on making points stated above work. &#xA;&#xA;The need to have manifest routes technique&#xA;&#xA;There is a subtle nuance that is missing when following traditional approaches to modularization. &#xA;&#xA;When adding an index file, as a part of the modularization process, exporting the content of directories, for that matter -- sub-directories, does not result in exporting routes that can be plugged into existing expressjs applications. &#xA;&#xA;The remedy is to create, isolate, export, and manifest them to the outer world.   &#xA;&#xA;How to apply the manifest routes handlers for reusability&#xA;&#xA;The handlers are a beast in their own way. &#xA;&#xA;A collection of related route handlers can be used as a baseline to create the controller layer. The modularization of this newly created/revealed layer can be achieved in two steps as was the case for other use cases. The first step consists of naming, ejecting, and exporting single functions as modules. The second step consists of adding an index to every directory and exporting the content of the directory.&#xA;&#xA;Manifest routes&#xA;&#xA;In essence, requiring a top-level directory, will seek for index.js at top of the directory and make all the route content accessible to the caller. &#xA;&#xA;var routes = require(&#39;./routes&#39;); &#xA;Example: /routes has index.js at top level directory ~ source&#xA;&#xA;A typical default entry point of the application: &#xA;&#xA;var express = require(&#39;express&#39;);  &#xA;var router = express.Router();&#xA;&#xA;router.get(&#39;/&#39;, function(req, res, next) {  &#xA;  return res.render(&#39;index&#39;, { title: &#39;Express&#39; });&#xA;});&#xA;module.exports = router;  &#xA;Example: default /index entry point&#xA;&#xA;Anatomy of a route handler &#xA;&#xA;module.exports = function (req, res) {  };&#xA;Example: routes/users/get-user|new-user|delete-user.js&#xA;&#xA;  &#34;The most elegant configuration that I&#39;ve found is to turn the larger routes with lots of sub-routes into a directory instead of a single route file&#34; - Chev  source&#xA;&#xA;When individual routes/users sub-directories are put together, the resulting index would look as in the following code sample &#xA;&#xA;var router = require(&#39;express&#39;).Router();  &#xA;router.get(&#39;/get/:id&#39;, require(&#39;./get-user.js&#39;));  &#xA;router.post(&#39;/new&#39;, require(&#39;./new-user.js&#39;));  &#xA;router.post(&#39;/delete/:id&#39;, require(&#39;./delete-user.js&#39;));  &#xA;module.exports = router;    &#xA;Example: routes/users/index.js&#xA;&#xA;Update when routes/users/favorites/ adds more sub-directories&#xA;&#xA;router.use(&#39;/favorites&#39;, require(&#39;./favorites&#39;)); &#xA;...&#xA;module.exports = router;&#xA;Example: routes/users/index.js ~ after adding a new favorites requirement&#xA;&#xA;We can go extra mile and group route handlers in controllers. Using route and controllers&#39; route handler as a controller would look as in the following example:&#xA;&#xA;var router = require(&#39;express&#39;).Router();&#xA;var catalogues = require(&#39;./controllers/catalogues&#39;);&#xA;&#xA;router.route(&#39;/catalogues&#39;)&#xA;  .get(catalogues.getItem)&#xA;  .post(catalogues.createItem);&#xA;module.exports = router;&#xA;&#xA;Conclusion &#xA;&#xA;Modularization makes expressjs routes reusable, composable, and stable as the rest of the system evolves. Modularization brings elegance to route composition, improved testability, and reduces instances of redundancy. &#xA;&#xA;In this article, we revisited a technique that improves expressjs routes elegance, their testability, and re-usability known under the manifest route moniker. We also re-state that the manifest route technique is an extra mile to modularizing expressjs routes. There are additional complimentary materials in the &#34;Testing nodejs applications&#34; book. &#xA;&#xA;References &#xA;&#xA;Testing nodejs Applications book&#xA;An Intuitive Way To Organize Your expressjs Routes ~ CodeTunnel&#xA;&#xA;#snippets #modularization #manifest-routes #nodejs #expressjs]]&gt;</description>
      <content:encoded><![CDATA[<p>We assume most of the system components to be accessible for testability. However, that is challenging when routes are a little bit complex. To reduce the complexity that comes with working on large-scale <code>expressjs</code> routes, we will apply a technique known as <em>manifest routes</em> to make route declarations change proof, making them more stable as the rest of the application evolves.</p>

<p><strong><em>In this article we will talk about:</em></strong></p>
<ul><li>The need to have manifest routes technique</li>
<li>How to apply the manifest routes as a modularization technique</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 express = require(&#39;express&#39;)
var app = express();

app.get(&#39;/&#39;, function(req, res, next) {  
  res.render(&#39;index&#39;, { title: &#39;Express&#39; });
});

/** code that initialize everything, then comes this route*/
app.get(&#39;/users/:id&#39;, function(req, res, next){
  User.findById(req.params.id, function(error, user){
    if(error) return next(error);
    return res.status(200).json(user);
  });
});

app.listen(port, function () {
  console.log(&#39;Example app listening on port 3000!&#39;)
});

</code></pre>

<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 modularization of <code>expressjs</code> routes with a manifest route pattern, the following points may be a challenge:</p>
<ul><li>Where to start with modularization without breaking the rest of the application</li>
<li>How to introduce the layered architecture, without incurring additional test burden, but making it easier to isolate tests</li></ul>

<p>The following sections will explore more on making points stated above work.</p>

<h2 id="the-need-to-have-manifest-routes-technique" id="the-need-to-have-manifest-routes-technique">The need to have manifest routes technique</h2>

<p>There is a subtle nuance that is missing when following traditional approaches to modularization.</p>

<p>When adding an <code>index</code> file, as a part of the modularization process, exporting the content of directories, for that matter — sub-directories, does not result in exporting routes that can be plugged into existing <code>expressjs</code> applications.</p>

<p>The remedy is to create, isolate, export, and manifest them to the outer world.</p>

<h2 id="how-to-apply-the-manifest-routes-handlers-for-reusability" id="how-to-apply-the-manifest-routes-handlers-for-reusability">How to apply the manifest routes handlers for reusability</h2>

<p>The handlers are a beast in their own way.</p>

<p>A collection of related route handlers can be used as a baseline to create the controller layer. The modularization of this newly created/revealed layer can be achieved in two steps as was the case for other use cases. The first step consists of naming, ejecting, and exporting single functions as modules. The second step consists of adding an <code>index</code> to every directory and exporting the content of the directory.</p>

<h2 id="manifest-routes" id="manifest-routes">Manifest routes</h2>

<p>In essence, requiring a top-level directory, will seek for <code>index.js</code> at top of the directory and make all the route content accessible to the caller.</p>

<pre><code class="language-JavaScript">var routes = require(&#39;./routes&#39;); 
</code></pre>

<p><em><em>Example</em>: <code>/routes</code> has <code>index.js</code> at top level directory ~ <a href="http://stackoverflow.com/a/5365577/132610">source</a></em></p>

<p>A typical default entry point of the application:</p>

<pre><code class="language-JavaScript">var express = require(&#39;express&#39;);  
var router = express.Router();

router.get(&#39;/&#39;, function(req, res, next) {  
  return res.render(&#39;index&#39;, { title: &#39;Express&#39; });
});
module.exports = router;  
</code></pre>

<p><em><em>Example</em>: default <code>/index</code> entry point</em></p>

<p>Anatomy of a route handler</p>

<pre><code class="language-JavaScript">module.exports = function (req, res) {  };
</code></pre>

<p><em><em>Example</em>: <code>routes/users/get-user|new-user|delete-user.js</code></em></p>

<blockquote><p><em>“The most elegant configuration that I&#39;ve found is to turn the larger routes with lots of sub-routes into a directory instead of a single route file”</em> – Chev  <a href="https://codetunnel.io/an-intuitive-way-to-organize-your-expressjs-routes/">source</a></p></blockquote>

<p>When individual routes/users sub-directories are put together, the resulting index would look as in the following code sample</p>

<pre><code class="language-JavaScript">var router = require(&#39;express&#39;).Router();  
router.get(&#39;/get/:id&#39;, require(&#39;./get-user.js&#39;));  
router.post(&#39;/new&#39;, require(&#39;./new-user.js&#39;));  
router.post(&#39;/delete/:id&#39;, require(&#39;./delete-user.js&#39;));  
module.exports = router;    
</code></pre>

<p><em><em>Example</em>: <code>routes/users/index.js</code></em></p>

<p>Update when <code>routes/users/favorites/</code> adds more sub-directories</p>

<pre><code class="language-JavaScript">router.use(&#39;/favorites&#39;, require(&#39;./favorites&#39;)); 
...
module.exports = router;
</code></pre>

<p><em><em>Example</em>: <code>routes/users/index.js</code> ~ after adding a new favorites requirement</em></p>

<p>We can go extra mile and group route handlers in controllers. Using route and controllers&#39; route handler as a controller would look as in the following example:</p>

<pre><code class="language-JavaScript">var router = require(&#39;express&#39;).Router();
var catalogues = require(&#39;./controllers/catalogues&#39;);

router.route(&#39;/catalogues&#39;)
  .get(catalogues.getItem)
  .post(catalogues.createItem);
module.exports = router;
</code></pre>

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

<p>Modularization makes <code>expressjs</code> routes reusable, composable, and stable as the rest of the system evolves. Modularization brings elegance to route composition, improved testability, and reduces instances of redundancy.</p>

<p>In this article, we revisited a technique that improves <code>expressjs</code> routes elegance, their testability, and re-usability known under the manifest route moniker. We also re-state that the manifest route technique is an extra mile to modularizing <code>expressjs</code> routes. 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>An Intuitive Way To Organize Your <code>expressjs</code> Routes ~ <a href="https://codetunnel.io/an-intuitive-way-to-organize-your-expressjs-routes/">CodeTunnel</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:modularization" class="hashtag"><span>#</span><span class="p-category">modularization</span></a> <a href="https://getsimple.works/tag:manifest" class="hashtag"><span>#</span><span class="p-category">manifest</span></a>-routes <a href="https://getsimple.works/tag:nodejs" class="hashtag"><span>#</span><span class="p-category">nodejs</span></a> <a href="https://getsimple.works/tag:expressjs" class="hashtag"><span>#</span><span class="p-category">expressjs</span></a></p>
]]></content:encoded>
      <guid>https://getsimple.works/modularizing-nodejs-applications-manifest-routes</guid>
      <pubDate>Thu, 17 Jun 2021 05:46:06 +0000</pubDate>
    </item>
    <item>
      <title>Testing expressjs routes without spinning up a server.</title>
      <link>https://getsimple.works/testing-expressjs-routes-without-spinning-up-a-server-y33d?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[In most integration and end-to-end routes testing, a live server may be deemed critical to make reasonable test assertions. A live server is not always a good idea, especially in a sandboxed environment such as a CI environment where opening server ports may be restricted, if not outright prohibited. In this article, we explore the combination of mocking HTTP requests/responses to make use of an actual server obsolete. &#xA;&#xA;In this article we will talk about: &#xA;&#xA;Mocking the Server instance  &#xA;Mocking Route&#39;s Request/Response objects&#xA;Modularization of routes and revealing server instance&#xA;Auto reload(hot reload) using:nodemon, supervisor or forever&#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;What can possibly go wrong?&#xA;&#xA;When trying to figure out how to approach testing expressjs routes, the driving force behind falling into the integration testing trap is the need to start a server. the following points may be a challenge:&#xA;&#xA;Routes should be served at any time while testing &#xA;Testing in a sandboxed environments restricts server to use(open new ports, serving requests, etc) &#xA;Mocking request/response objects to wipe need of a server out of the picture&#xA;&#xA;Testing routes without spinning up a server&#xA;&#xA;The key is mocking request/response objects. A typical REST integration testing shares similarities with the following snippet. &#xA;&#xA;var app = require(&#39;express&#39;).express(),&#xA;  request = require(&#39;./support/http&#39;);&#xA;&#xA;describe(&#39;req .route&#39;, function(){&#xA;  it(&#39;should serve on route /user/:id/edit&#39;, function(done){&#xA;    app.get(&#39;/user/:id/edit&#39;, function(req, res){&#xA;      expect(req.route.path).to.equal(&#39;/user/:id/edit&#39;);&#xA;      res.end();&#xA;    });&#xA;&#xA;    request(app)&#xA;      .get(&#39;/user/12/edit&#39;)&#xA;      .expect(200, done);&#xA;  });&#xA;  it(&#39;should serve get requests&#39;, function(done){&#xA;    app.get(&#39;/user/:id/edit&#39;, function(req, res){&#xA;      expect(req.route.method).to.equal(&#39;get&#39;);&#xA;      res.end();&#xA;    });&#xA;&#xA;    request(app)&#xA;    .get(&#39;/user/12/edit&#39;)&#xA;    .expect(200, done);&#xA;  });&#xA;});&#xA;Example:&#xA;&#xA;  example from so and supertest. supertest spins up a server if necessary. In case we don&#39;t want to have a server, then an alternative dupertest can be a reasonable alternative. request = require(&#39;./support/http&#39;) is the utility that may use either of those two libraries to provide a request. &#xA;&#xA;Choosing tools &#xA;&#xA;  If you haven&#39;t already, reading &#34;How to choose the right tools&#34; blog post gives insights on a framework we used to choose the tools we suggest in this blog. &#xA;&#xA;Following our own Choosing the right tools framework, we suggest adopting the following tools, when testing expressjs routes by mocking out the server: &#xA;&#xA;There exists well respected such as jasmine(jasmine-node), ava, jest in the wild. mocha can just do fine for example sakes. &#xA;There is also code instrumentation tools in the wild. mocha integrates well with istanbul test coverage and reporting library.&#xA;supertest,  nock and dupertest are framework for mocking mocking HTTP, whereas nock intercepts requests. dupertest responds better to our demands(not spinning up a server).  &#xA;&#xA;Workflow&#xA;&#xA;  If you haven&#39;t already, read the &#34;How to write test cases developers will love&#34;&#xA;&#xA;In package.json at &#34;test&#34; - add next line&#xA;  &#34;istanbul test mocha -- --color --reporter mocha-lcov-reporter specs&#34;&#xA;OR &#34;nyc test mocha -- --color --reporter mocha-lcov-reporter specs&#34;&#xA;&#xA;Then run the tests using &#xA;$ npm test --coverage &#xA;Example: istanbul generates reports as tests progress&#xA;&#xA;Conclusion&#xA;&#xA;To sum up, it pays off to spend extra time writing some tests. Effective tests can be written before, as well as after writing code. The balance should be at the discretion of the developer. &#xA;&#xA;Testing nodejs routes are quite intimidating on the first encounter. This article contributed to shifting fear into opportunities. &#xA;&#xA;Removing the server dependency makes it easy to validate the most common use cases at a lower cost. Writing a good meaningful message is pure art. There are additional complimentary materials in the &#34;Testing nodejs applications&#34; book. &#xA;&#xA;References&#xA;&#xA;Testing nodejs Applications book&#xA;A TDD Approach to Building a Todo API Using nodejs and mongodb ~ SemaphoreCI Community Tutorials&#xA;&#34;How to build and test REST with nodejs Express Mocha&#34; ~  The Way of Code&#xA;&#xA;#tdd #testing #nodejs #expressjs #server]]&gt;</description>
      <content:encoded><![CDATA[<p>In most integration and <em>end-to-end</em> routes testing, a live server may be deemed critical to make reasonable test assertions. A live server is not always a good idea, especially in a sandboxed environment such as a CI environment where opening server ports may be restricted, if not outright prohibited. In this article, we explore the combination of mocking HTTP requests/responses to make use of an actual server obsolete.</p>

<p><strong><em>In this article we will talk about:</em></strong></p>
<ul><li>Mocking the Server instance<br/></li>
<li>Mocking Route&#39;s Request/Response objects</li>
<li>Modularization of routes and revealing server instance</li>
<li>Auto reload(hot reload) using:<code>nodemon</code>, <code>supervisor</code> or <code>forever</code></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>

<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 testing <code>expressjs</code> routes, the driving force behind falling into the integration testing trap is the need to start a server. the following points may be a challenge:</p>
<ul><li>Routes should be served at any time while testing</li>
<li>Testing in a sandboxed environments restricts server to use(open new ports, serving requests, etc)</li>
<li>Mocking request/response objects to wipe need of a server out of the picture</li></ul>

<h2 id="testing-routes-without-spinning-up-a-server" id="testing-routes-without-spinning-up-a-server">Testing routes without spinning up a server</h2>

<p>The key is mocking request/response objects. A typical REST integration testing shares similarities with the following snippet.</p>

<pre><code class="language-JavaScript">
var app = require(&#39;express&#39;).express(),
  request = require(&#39;./support/http&#39;);

describe(&#39;req .route&#39;, function(){
  it(&#39;should serve on route /user/:id/edit&#39;, function(done){
    app.get(&#39;/user/:id/edit&#39;, function(req, res){
      expect(req.route.path).to.equal(&#39;/user/:id/edit&#39;);
      res.end();
    });

    request(app)
      .get(&#39;/user/12/edit&#39;)
      .expect(200, done);
  });
  it(&#39;should serve get requests&#39;, function(done){
    app.get(&#39;/user/:id/edit&#39;, function(req, res){
      expect(req.route.method).to.equal(&#39;get&#39;);
      res.end();
    });

    request(app)
    .get(&#39;/user/12/edit&#39;)
    .expect(200, done);
  });
});
</code></pre>

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

<blockquote><p>example from <a href="https://stackoverflow.com/a/14703801/132610">so</a> and <a href="https://github.com/visionmedia/express/tree/master/test"><code>supertest</code></a>. <code>supertest</code> spins up a server if necessary. In case we don&#39;t want to have a server, then an alternative <a href="https://www.npmjs.com/package/dupertest"><code>dupertest</code></a> can be a reasonable alternative. <code>request = require(&#39;./support/http&#39;)</code> is the utility that may use either of those two libraries to provide a request.</p></blockquote>

<h2 id="choosing-tools" id="choosing-tools">Choosing tools</h2>

<blockquote><p>If you haven&#39;t already, reading <a href="./how-to-choose-the-right-tools.md">“How to choose the right tools”</a> blog post gives insights on a framework we used to choose the tools we suggest in this blog.</p></blockquote>

<p>Following our own <em>Choosing the right tools</em> framework, we suggest adopting the following tools, when testing <code>expressjs</code> routes by mocking out the server:</p>
<ul><li>There exists well respected such as <code>jasmine</code>(<code>jasmine-node</code>), <code>ava</code>, <code>jest</code> in the wild. <code>mocha</code> can just do fine for example sakes.</li>
<li>There is also code instrumentation tools in the wild. <code>mocha</code> integrates well with <code>istanbul</code> test coverage and reporting library.</li>
<li><code>supertest</code>,  <code>nock</code> and <code>dupertest</code> are framework for mocking mocking HTTP, whereas <code>nock</code> intercepts requests. <code>dupertest</code> responds better to our demands(not spinning up a server).<br/></li></ul>

<h2 id="workflow" id="workflow">Workflow</h2>

<blockquote><p>If you haven&#39;t already, read the <a href="./how-to-write-test-cases-developers-will-love.md">“How to write test cases developers will love”</a></p></blockquote>

<pre><code class="language-shell"># In package.json at &#34;test&#34; - add next line
&gt; &#34;istanbul test mocha -- --color --reporter mocha-lcov-reporter specs&#34;
# OR &#34;nyc test mocha -- --color --reporter mocha-lcov-reporter specs&#34;

# Then run the tests using 
$ npm test --coverage 
</code></pre>

<p><em><em>Example</em>: <code>istanbul</code> generates reports as tests progress</em></p>

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

<p>To sum up, it pays off to spend extra time writing some tests. Effective tests can be written before, as well as after writing code. The balance should be at the discretion of the developer.</p>

<p>Testing <code>nodejs</code> routes are quite intimidating on the first encounter. This article contributed to shifting fear into opportunities.</p>

<p>Removing the server dependency makes it easy to validate the most common use cases at a lower cost. Writing a good meaningful message is pure art. There are additional complimentary materials in the <strong>“Testing <code>nodejs</code> applications”</strong> book.</p>

<h3 id="references" id="references">References</h3>
<ul><li><a href="https://bit.ly/2ZFJytb">Testing <code>nodejs</code> Applications book</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><em>“How to build and test REST with <code>nodejs</code> Express Mocha”</em> ~  <a href="https://thewayofcode.wordpress.com/2013/04/21/how-to-build-and-test-rest-api-with-nodejs-express-mocha/">The Way of Code</a></li></ul>

<p><a href="https://getsimple.works/tag:tdd" class="hashtag"><span>#</span><span class="p-category">tdd</span></a> <a href="https://getsimple.works/tag:testing" class="hashtag"><span>#</span><span class="p-category">testing</span></a> <a href="https://getsimple.works/tag:nodejs" class="hashtag"><span>#</span><span class="p-category">nodejs</span></a> <a href="https://getsimple.works/tag:expressjs" class="hashtag"><span>#</span><span class="p-category">expressjs</span></a> <a href="https://getsimple.works/tag:server" class="hashtag"><span>#</span><span class="p-category">server</span></a></p>
]]></content:encoded>
      <guid>https://getsimple.works/testing-expressjs-routes-without-spinning-up-a-server-y33d</guid>
      <pubDate>Thu, 17 Jun 2021 04:13:53 +0000</pubDate>
    </item>
    <item>
      <title>Testing expressjs routes without spinning up a server.</title>
      <link>https://getsimple.works/testing-expressjs-routes-without-spinning-up-a-server?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[In most integration and end-to-end routes testing, a live server may be deemed critical to make reasonable test assertions. A live server is not always a good idea, especially in a sandboxed environment such as a CI environment where opening server ports may be restricted, if not outright prohibited. In this article, we explore the combination of mocking HTTP requests/responses to make use of an actual server obsolete. &#xA;&#xA;In this article we will talk about: &#xA;&#xA;Mocking the Server instance  &#xA;Mocking Route&#39;s Request/Response objects&#xA;Modularization of routes and revealing server instance&#xA;Auto reload(hot reload) using:nodemon, supervisor or forever&#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;What can possibly go wrong?&#xA;&#xA;When trying to figure out how to approach testing expressjs routes, the driving force behind falling into the integration testing trap is the need to start a server. the following points may be a challenge:&#xA;&#xA;Routes should be served at any time while testing &#xA;Testing in a sandboxed environments restricts server to use(open new ports, serving requests, etc) &#xA;Mocking request/response objects to wipe need of a server out of the picture&#xA;&#xA;Testing routes without spinning up a server&#xA;&#xA;The key is mocking request/response objects. A typical REST integration testing shares similarities with the following snippet. &#xA;&#xA;var app = require(&#39;express&#39;).express(),&#xA;  request = require(&#39;./support/http&#39;);&#xA;&#xA;describe(&#39;req .route&#39;, function(){&#xA;  it(&#39;should serve on route /user/:id/edit&#39;, function(done){&#xA;    app.get(&#39;/user/:id/edit&#39;, function(req, res){&#xA;      expect(req.route.path).to.equal(&#39;/user/:id/edit&#39;);&#xA;      res.end();&#xA;    });&#xA;&#xA;    request(app)&#xA;      .get(&#39;/user/12/edit&#39;)&#xA;      .expect(200, done);&#xA;  });&#xA;  it(&#39;should serve get requests&#39;, function(done){&#xA;    app.get(&#39;/user/:id/edit&#39;, function(req, res){&#xA;      expect(req.route.method).to.equal(&#39;get&#39;);&#xA;      res.end();&#xA;    });&#xA;&#xA;    request(app)&#xA;    .get(&#39;/user/12/edit&#39;)&#xA;    .expect(200, done);&#xA;  });&#xA;});&#xA;Example:&#xA;&#xA;  example from so and supertest. supertest spins up a server if necessary. In case we don&#39;t want to have a server, then an alternative dupertest can be a reasonable alternative. request = require(&#39;./support/http&#39;) is the utility that may use either of those two libraries to provide a request. &#xA;&#xA;Choosing tools &#xA;&#xA;  If you haven&#39;t already, reading &#34;How to choose the right tools&#34; blog post gives insights on a framework we used to choose the tools we suggest in this blog. &#xA;&#xA;Following our own Choosing the right tools framework, we suggest adopting the following tools, when testing expressjs routes by mocking out the server: &#xA;&#xA;There exists well respected such as jasmine(jasmine-node), ava, jest in the wild. mocha can just do fine for example sakes. &#xA;There is also code instrumentation tools in the wild. mocha integrates well with istanbul test coverage and reporting library.&#xA;supertest,  nock and dupertest are framework for mocking mocking HTTP, whereas nock intercepts requests. dupertest responds better to our demands(not spinning up a server).  &#xA;&#xA;Workflow&#xA;&#xA;  If you haven&#39;t already, read the &#34;How to write test cases developers will love&#34;&#xA;&#xA;In package.json at &#34;test&#34; - add next line&#xA;  &#34;istanbul test mocha -- --color --reporter mocha-lcov-reporter specs&#34;&#xA;OR &#34;nyc test mocha -- --color --reporter mocha-lcov-reporter specs&#34;&#xA;&#xA;Then run the tests using &#xA;$ npm test --coverage &#xA;Example: istanbul generates reports as tests progress&#xA;&#xA;Conclusion&#xA;&#xA;To sum up, it pays off to spend extra time writing some tests. Effective tests can be written before, as well as after writing code. The balance should be at the discretion of the developer. &#xA;&#xA;Testing nodejs routes are quite intimidating on the first encounter. This article contributed to shifting fear into opportunities. &#xA;&#xA;Removing the server dependency makes it easy to validate the most common use cases at a lower cost. Writing a good meaningful message is pure art. There are additional complimentary materials in the &#34;Testing nodejs applications&#34; book. &#xA;&#xA;References&#xA;&#xA;Testing nodejs Applications book&#xA;A TDD Approach to Building a Todo API Using nodejs and mongodb ~ SemaphoreCI Community Tutorials&#xA;&#34;How to build and test REST with nodejs Express Mocha&#34; ~  The Way of Code&#xA;&#xA;#tdd #testing #nodejs #expressjs #server]]&gt;</description>
      <content:encoded><![CDATA[<p>In most integration and <em>end-to-end</em> routes testing, a live server may be deemed critical to make reasonable test assertions. A live server is not always a good idea, especially in a sandboxed environment such as a CI environment where opening server ports may be restricted, if not outright prohibited. In this article, we explore the combination of mocking HTTP requests/responses to make use of an actual server obsolete.</p>

<p><strong><em>In this article we will talk about:</em></strong></p>
<ul><li>Mocking the Server instance<br/></li>
<li>Mocking Route&#39;s Request/Response objects</li>
<li>Modularization of routes and revealing server instance</li>
<li>Auto reload(hot reload) using:<code>nodemon</code>, <code>supervisor</code> or <code>forever</code></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>

<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 testing <code>expressjs</code> routes, the driving force behind falling into the integration testing trap is the need to start a server. the following points may be a challenge:</p>
<ul><li>Routes should be served at any time while testing</li>
<li>Testing in a sandboxed environments restricts server to use(open new ports, serving requests, etc)</li>
<li>Mocking request/response objects to wipe need of a server out of the picture</li></ul>

<h2 id="testing-routes-without-spinning-up-a-server" id="testing-routes-without-spinning-up-a-server">Testing routes without spinning up a server</h2>

<p>The key is mocking request/response objects. A typical REST integration testing shares similarities with the following snippet.</p>

<pre><code class="language-JavaScript">
var app = require(&#39;express&#39;).express(),
  request = require(&#39;./support/http&#39;);

describe(&#39;req .route&#39;, function(){
  it(&#39;should serve on route /user/:id/edit&#39;, function(done){
    app.get(&#39;/user/:id/edit&#39;, function(req, res){
      expect(req.route.path).to.equal(&#39;/user/:id/edit&#39;);
      res.end();
    });

    request(app)
      .get(&#39;/user/12/edit&#39;)
      .expect(200, done);
  });
  it(&#39;should serve get requests&#39;, function(done){
    app.get(&#39;/user/:id/edit&#39;, function(req, res){
      expect(req.route.method).to.equal(&#39;get&#39;);
      res.end();
    });

    request(app)
    .get(&#39;/user/12/edit&#39;)
    .expect(200, done);
  });
});
</code></pre>

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

<blockquote><p>example from <a href="https://stackoverflow.com/a/14703801/132610">so</a> and <a href="https://github.com/visionmedia/express/tree/master/test"><code>supertest</code></a>. <code>supertest</code> spins up a server if necessary. In case we don&#39;t want to have a server, then an alternative <a href="https://www.npmjs.com/package/dupertest"><code>dupertest</code></a> can be a reasonable alternative. <code>request = require(&#39;./support/http&#39;)</code> is the utility that may use either of those two libraries to provide a request.</p></blockquote>

<h2 id="choosing-tools" id="choosing-tools">Choosing tools</h2>

<blockquote><p>If you haven&#39;t already, reading <a href="./how-to-choose-the-right-tools.md">“How to choose the right tools”</a> blog post gives insights on a framework we used to choose the tools we suggest in this blog.</p></blockquote>

<p>Following our own <em>Choosing the right tools</em> framework, we suggest adopting the following tools, when testing <code>expressjs</code> routes by mocking out the server:</p>
<ul><li>There exists well respected such as <code>jasmine</code>(<code>jasmine-node</code>), <code>ava</code>, <code>jest</code> in the wild. <code>mocha</code> can just do fine for example sakes.</li>
<li>There is also code instrumentation tools in the wild. <code>mocha</code> integrates well with <code>istanbul</code> test coverage and reporting library.</li>
<li><code>supertest</code>,  <code>nock</code> and <code>dupertest</code> are framework for mocking mocking HTTP, whereas <code>nock</code> intercepts requests. <code>dupertest</code> responds better to our demands(not spinning up a server).<br/></li></ul>

<h2 id="workflow" id="workflow">Workflow</h2>

<blockquote><p>If you haven&#39;t already, read the <a href="./how-to-write-test-cases-developers-will-love.md">“How to write test cases developers will love”</a></p></blockquote>

<pre><code class="language-shell"># In package.json at &#34;test&#34; - add next line
&gt; &#34;istanbul test mocha -- --color --reporter mocha-lcov-reporter specs&#34;
# OR &#34;nyc test mocha -- --color --reporter mocha-lcov-reporter specs&#34;

# Then run the tests using 
$ npm test --coverage 
</code></pre>

<p><em><em>Example</em>: <code>istanbul</code> generates reports as tests progress</em></p>

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

<p>To sum up, it pays off to spend extra time writing some tests. Effective tests can be written before, as well as after writing code. The balance should be at the discretion of the developer.</p>

<p>Testing <code>nodejs</code> routes are quite intimidating on the first encounter. This article contributed to shifting fear into opportunities.</p>

<p>Removing the server dependency makes it easy to validate the most common use cases at a lower cost. Writing a good meaningful message is pure art. There are additional complimentary materials in the <strong>“Testing <code>nodejs</code> applications”</strong> book.</p>

<h3 id="references" id="references">References</h3>
<ul><li><a href="https://bit.ly/2ZFJytb">Testing <code>nodejs</code> Applications book</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><em>“How to build and test REST with <code>nodejs</code> Express Mocha”</em> ~  <a href="https://thewayofcode.wordpress.com/2013/04/21/how-to-build-and-test-rest-api-with-nodejs-express-mocha/">The Way of Code</a></li></ul>

<p><a href="https://getsimple.works/tag:tdd" class="hashtag"><span>#</span><span class="p-category">tdd</span></a> <a href="https://getsimple.works/tag:testing" class="hashtag"><span>#</span><span class="p-category">testing</span></a> <a href="https://getsimple.works/tag:nodejs" class="hashtag"><span>#</span><span class="p-category">nodejs</span></a> <a href="https://getsimple.works/tag:expressjs" class="hashtag"><span>#</span><span class="p-category">expressjs</span></a> <a href="https://getsimple.works/tag:server" class="hashtag"><span>#</span><span class="p-category">server</span></a></p>
]]></content:encoded>
      <guid>https://getsimple.works/testing-expressjs-routes-without-spinning-up-a-server</guid>
      <pubDate>Thu, 17 Jun 2021 00:33:29 +0000</pubDate>
    </item>
    <item>
      <title>Testing expressjs Routes </title>
      <link>https://getsimple.works/testing-expressjs-routes?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This blog post approaches testing fairly large nodejs application from a real-world perspective and with refactoring in mind. The use cases address advanced concepts that testing expressjs routes are.&#xA;&#xA;Automated testing of any JavaScript project is quite intimidating for newbies and veterans alike. &#xA;&#xA;In this article we will talk about: &#xA;&#xA;Healthy test coverage of routes&#xA;Modularization of routes for testability  &#xA;Mock Route&#39;s Request/Response Objects when necessary&#xA;Mock requests to third-party endpoints such as Payment Gateway.&#xA;&#xA;Additional challenges while testing expressjs Routes&#xA;&#xA;Test code, not the output &#xA;Mock requests to Payment Gateway, etc.&#xA;Mock database read/write operations&#xA;Be able to cover exceptions and missing data structures&#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 getProfile = require(&#39;./settings/get-profile&#39;);&#xA;router.get(&#39;/profile/:id&#39;, authenticated, getProfile);&#xA;module.exports = router;&#xA;Example*:&#xA;&#xA;What can possibly go wrong?&#xA;&#xA;When (unit) test expressjs routes the following challenges may arise:&#xA;&#xA;Drawing a line between tests that fall into the unit testing category versus those tests that fall into the integration testing camp.&#xA;Being mindful that authenticated routes can appeal in the picture&#xA;Mock database read/write operations, or other layers(controller/service) that are not critical (core) to validation of the route&#39;s expectations&#xA;&#xA;Choosing tools &#xA;&#xA;  If you haven&#39;t already, reading &#34;How to choose the right tools&#34; blog post gives insights on a framework we used to choose the tools we suggest in this blog. &#xA;&#xA;Following our own Choosing the right tools framework, we suggest adopting the following tools, when testing expressjs routes: &#xA;&#xA;We can technically have auto-reload or hot-reload using: pm2, nodemon or forever. We recommend supervisor.&#xA;We can choose amongst a myriad of test runners, for instance, jasmine(jasmine-node), ava or jest. We recommend mocha. The stack mocha, chai and sinon can be worth it as well.  &#xA;supertest framework for mocking Restful APIs and nock for mocking  HTTP. &#xA;Code under test is instrumented, but default reporting tools do not always suit our every project&#39;s needs. For test coverage reporting we recommend istanbul. &#xA;&#xA;Workflow&#xA;&#xA;It is possible to generate reports as tests progress. &#xA;&#xA;  latest versions of istanbul uses nyc name.&#xA;&#xA;In package.json at &#34;test&#34; - add next line&#xA;  &#34;istanbul test mocha -- --color --reporter mocha-lcov-reporter specs&#34;&#xA;&#xA;Then run the tests using &#xA;$ npm test --coverage &#xA;&#xA;Show me the test&#xA;&#xA;  If you haven&#39;t already, read the &#34;How to write test cases developers will love&#34;&#xA;&#xA;The mainstream philosophy about automated testing is to write failing tests, followed by code that resolves the failing use cases. This is not always the case, especially when dealing with legacy code, or poorly tested code. The less puritan approach is at least tests when the code is still fresh in memory.  &#xA;&#xA;  In this article, we assume the reader knows how to mock routes, otherwise there are articles that cover the basics of mocking routes&#39; request/response objects and how to mock database read/write functions in this blog.&#xA;&#xA;The common source of frustration and sometimes bad decision-making that follows is when not able to define boundaries: when to start refactoring, and when to stop. &#xA;&#xA;Testing a route handler in isolation looks like testing any function. In our case, there should be a mocking operation of the User.findById() function, that is intended to be used with the request.  &#xA;&#xA;  For more on how to mock mongoose read/write function. &#xA;&#xA;describe(&#39;getProfile&#39;, () =  {&#xA;  let req, res, next, error;&#xA;  beforeEach(() =  {&#xA;    next = sinon.spy();&#xA;    sessionObject = { ... };//mocking session object&#xA;    req = { params: {id: 1234}, user: sessionObject };&#xA;    res = { status: (code) =  { json: sinon.spy() }}&#xA;  });&#xA;&#xA;  it(&#39;returns a profile&#39;, () =  {&#xA;    getRequest(req, res, next);&#xA;    expect(res.status().json).toHaveBeenCalled();&#xA;  });&#xA;  &#xA;  it(&#39;fails when no profile is found&#39;, () =  {&#xA;    getRequest(req, res, next);&#xA;    expect(next).toHaveBeenCalledWith([error, null]);&#xA;  });&#xA;&#xA;});&#xA;&#xA;  Please refer to this article to learn more about how to mocking mongoose read/write functions(./how-to-stub-mongoose-methods-and-mock-document-objects)). &#xA;&#xA;Testing an integral route falls into the integration testing category. Whether we connect to a live database or use a live server route is up to the programmer, but the best(fast/efficient) approach is to mock out those two expensive parts as well. &#xA;&#xA;var router = require(&#39;./profile/router&#39;),&#xA;    request = require(&#39;./support/http&#39;);&#xA;describe(&#39;/profile/:id&#39;, () =  {&#xA;  it(&#39;returns a profile&#39;, done =  {&#xA;    request(router)&#xA;      .get(&#39;/profile/12&#39;)&#xA;      .expect(200, done);&#xA;  });&#xA;&#xA;  it(&#39;fails when no profile is found&#39;, done =  {&#xA;    request(router)&#xA;      .get(&#39;/profile/NONEXISTENT&#39;)&#xA;      .expect(500, done);&#xA;  });&#xA;});&#xA;  request = require(&#39;./support/http&#39;) is the utility that may use either of supertest or dupertest provide a request.&#xA;&#xA;Conclusion&#xA;&#xA;When paying off technical debt, small bad moves can build up into catastrophe, such as downtime with little failure traceability. Good test coverage increase confidence when refactoring, refines boundaries, while at the same time reducing the introduction of new bugs in the codebase. &#xA;&#xA;In this article, we reviewed how testing tends to be more of art, than science. We also stressed the fact that, like in any art, practice makes perfect ~ testing routes, just like testing controllers, can be challenging when interacting with external systems is involved. There are additional complimentary materials in the &#34;Testing nodejs applications&#34; book. &#xA;&#xA;References&#xA;&#xA;Testing nodejs Applications book&#xA;nodejs testing essentials ~ Fred K. Schott&#xA;Testing expressjs REST APIs with mocha ~ Elliot Blog&#xA;Marcus on supertest ~ Marcus Soft Blog&#xA;&#34;How to build and test REST with nodejs Express Mocha&#34; ~ The Way of Code&#xA;A TDD Approach to Building a Todo API Using nodejs and mongodb ~ SemaphoreCI Community Tutorials&#xA;&#xA;#snippets #expressjs #routes #discuss]]&gt;</description>
      <content:encoded><![CDATA[<p>This blog post approaches testing fairly large <code>nodejs</code> application from a real-world perspective and with refactoring in mind. The use cases address advanced concepts that testing <code>expressjs</code> routes are.</p>

<p>Automated testing of any JavaScript project is quite intimidating for newbies and veterans alike.</p>

<p><strong><em>In this article we will talk about:</em></strong></p>
<ul><li>Healthy test coverage of routes</li>
<li>Modularization of routes for testability<br/></li>
<li>Mock Route&#39;s Request/Response Objects when necessary</li>
<li>Mock requests to third-party endpoints such as Payment Gateway.</li></ul>

<p>Additional challenges while testing <code>expressjs</code> Routes*</p>
<ul><li>Test code, not the output</li>
<li>Mock requests to Payment Gateway, etc.</li>
<li>Mock database read/write operations</li>
<li>Be able to cover exceptions and missing data structures</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 getProfile = require(&#39;./settings/get-profile&#39;);
router.get(&#39;/profile/:id&#39;, authenticated, getProfile);
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>When (unit) test <code>expressjs</code> routes the following challenges may arise:</p>
<ul><li>Drawing a line between tests that fall into the unit testing category versus those tests that fall into the integration testing camp.</li>
<li>Being mindful that authenticated routes can appeal in the picture</li>
<li>Mock database read/write operations, or other layers(controller/service) that are not critical (core) to validation of the route&#39;s expectations</li></ul>

<h2 id="choosing-tools" id="choosing-tools">Choosing tools</h2>

<blockquote><p>If you haven&#39;t already, reading <a href="./how-to-choose-the-right-tools.md">“How to choose the right tools”</a> blog post gives insights on a framework we used to choose the tools we suggest in this blog.</p></blockquote>

<p>Following our own <em>Choosing the right tools</em> framework, we suggest adopting the following tools, when testing <code>expressjs</code> routes:</p>
<ul><li>We can technically have auto-reload or hot-reload using: <code>pm2</code>, <code>nodemon</code> or <code>forever</code>. We recommend <code>supervisor</code>.</li>
<li>We can choose amongst a myriad of test runners, for instance, <code>jasmine</code>(<code>jasmine-node</code>), <code>ava</code> or <code>jest</code>. We recommend <code>mocha</code>. The stack <code>mocha</code>, <code>chai</code> and <code>sinon</code> can be worth it as well.<br/></li>
<li><code>supertest</code> framework for mocking Restful APIs and <code>nock</code> for mocking  HTTP.</li>
<li>Code under test is instrumented, but default reporting tools do not always suit our every project&#39;s needs. For test coverage reporting we recommend <code>istanbul</code>.</li></ul>

<h2 id="workflow" id="workflow">Workflow</h2>

<p>It is possible to generate reports as tests progress.</p>

<blockquote><p>latest versions of <code>istanbul</code> uses <code>nyc</code> name.</p></blockquote>

<pre><code class="language-shell"># In package.json at &#34;test&#34; - add next line
&gt; &#34;istanbul test mocha -- --color --reporter mocha-lcov-reporter specs&#34;

# Then run the tests using 
$ npm test --coverage 
</code></pre>

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

<blockquote><p>If you haven&#39;t already, read the <a href="./how-to-write-test-cases-developers-will-love.md">“How to write test cases developers will love”</a></p></blockquote>

<p>The mainstream philosophy about automated testing is to write failing tests, followed by code that resolves the failing use cases. This is not always the case, especially when dealing with legacy code, or poorly tested code. The less puritan approach is at least tests when the code is still fresh in memory.</p>

<blockquote><p>In this article, we assume the reader knows how to mock routes, otherwise there are articles that cover the basics of <a href="./how-to-stub-http-requests">mocking routes&#39; request/response objects</a> and <a href="./how-to-stub-mongoose-methods-and-mock-document-objects">how to mock database read/write functions</a> in this blog.</p></blockquote>

<p>The common source of frustration and sometimes bad decision-making that follows is when not able to define boundaries: when to start refactoring, and when to stop.</p>

<p>Testing a route handler in isolation looks like testing any function. In our case, there should be a mocking operation of the <code>User.findById()</code> function, that is intended to be used with the request.</p>

<blockquote><p>For more on <a href="./how-to-stub-mongoose-methods-and-mock-document-objects">how to mock mongoose read/write function</a>.</p></blockquote>

<pre><code class="language-JavaScript">describe(&#39;getProfile&#39;, () =&gt; {
  let req, res, next, error;
  beforeEach(() =&gt; {
    next = sinon.spy();
    sessionObject = { ... };//mocking session object
    req = { params: {id: 1234}, user: sessionObject };
    res = { status: (code) =&gt; { json: sinon.spy() }}
  });

  it(&#39;returns a profile&#39;, () =&gt; {
    getRequest(req, res, next);
    expect(res.status().json).toHaveBeenCalled();
  });
  
  it(&#39;fails when no profile is found&#39;, () =&gt; {
    getRequest(req, res, next);
    expect(next).toHaveBeenCalledWith([error, null]);
  });

});
</code></pre>

<blockquote><p>Please refer to this article to learn more about <a href="](./how-to-stub-mongoose-methods-and-mock-document-objects)">how to mocking mongoose read/write functions</a>.</p></blockquote>

<p>Testing an integral route falls into the integration testing category. Whether we connect to a live database or use a live server route is up to the programmer, but the best(fast/efficient) approach is to mock out those two expensive parts as well.</p>

<pre><code class="language-JavaScript">var router = require(&#39;./profile/router&#39;),
    request = require(&#39;./support/http&#39;);
describe(&#39;/profile/:id&#39;, () =&gt; {
  it(&#39;returns a profile&#39;, done =&gt; {
    request(router)
      .get(&#39;/profile/12&#39;)
      .expect(200, done);
  });

  it(&#39;fails when no profile is found&#39;, done =&gt; {
    request(router)
      .get(&#39;/profile/NONEXISTENT&#39;)
      .expect(500, done);
  });
});
</code></pre>

<blockquote><p> <code>request = require(&#39;./support/http&#39;)</code> is the utility that may use either of <code>supertest</code> or <code>dupertest</code> provide a request.</p></blockquote>

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

<p>When paying off technical debt, small bad moves can build up into catastrophe, such as downtime with little failure traceability. Good test coverage increase confidence when refactoring, refines boundaries, while at the same time reducing the introduction of new bugs in the codebase.</p>

<p>In this article, we reviewed how testing tends to be more of art, than science. We also stressed the fact that, like in any art, practice makes perfect ~ testing routes, just like testing controllers, can be challenging when interacting with external systems is involved. 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><code>nodejs</code> testing essentials ~ <a href="https://fredkschott.com/post/2014/05/nodejs-testing-essentials/">Fred K. Schott</a></li>
<li>Testing <code>expressjs</code> REST APIs with <code>mocha</code> ~ <a href="https://51elliot.blogspot.ca/2013/08/testing-expressjs-rest-api-with-mocha.html">Elliot Blog</a></li>
<li>Marcus on <code>supertest</code> ~ <a href="https://www.marcusoft.net/2014/02/mnb-supertest.html">Marcus Soft Blog</a></li>
<li><em>“How to build and test REST with <code>nodejs</code> Express Mocha”</em> ~ <a href="https://thewayofcode.wordpress.com/2013/04/21/how-to-build-and-test-rest-api-with-nodejs-express-mocha/">The Way of Code</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></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:expressjs" class="hashtag"><span>#</span><span class="p-category">expressjs</span></a> <a href="https://getsimple.works/tag:routes" class="hashtag"><span>#</span><span class="p-category">routes</span></a> <a href="https://getsimple.works/tag:discuss" class="hashtag"><span>#</span><span class="p-category">discuss</span></a></p>
]]></content:encoded>
      <guid>https://getsimple.works/testing-expressjs-routes</guid>
      <pubDate>Thu, 17 Jun 2021 00:19:52 +0000</pubDate>
    </item>
  </channel>
</rss>