<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>bdd &amp;mdash; Simple Engineering</title>
    <link>https://getsimple.works/tag:bdd</link>
    <description></description>
    <pubDate>Thu, 30 Apr 2026 22:49:53 +0000</pubDate>
    <item>
      <title>Overview on testing nodejs applications </title>
      <link>https://getsimple.works/overview-on-testing-nodejs-applications?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[This post highlights snapshots on best practices/hacks, to code, test, deploy and to maintain large-scale nodejs apps. It provides big lines on what became a book on testing nodejs applications.  &#xA;&#xA;  If you haven&#39;t yet, read the How to make nodejs applications modular article. This article is an overall follow-up.&#xA;&#xA;Like some of the articles that came before this one, we are going to focus on a simple question as our north star: What are the most important questions developers have when testing a nodejs application? When possible a quick answer will be provided, else we will point in the right direction where information can be found. &#xA;&#xA;In this article we will talk about: &#xA;&#xA;BDD versus TDD &#xA;Choosing the right testing tools &#xA;Testing servers&#xA;Testing modules &#xA;Testing routes&#xA;Testing controllers &#xA;Testing services &#xA;Testing middleware &#xA;Testing asynchronous code&#xA;Testing models&#xA;Testing WebSockets &#xA;Testing background jobs &#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;  app = express(),&#xA;  server = require(&#39;http&#39;).createServer(app);&#xA;//...&#xA;require(&#39;./config&#39;);&#xA;require(&#39;./utils/mongodb&#39;);&#xA;require(&#39;./utils/middleware&#39;)(app);&#xA;require(&#39;./routes&#39;)(app);&#xA;require(&#39;./realtime&#39;)(app, server)&#xA;//...&#xA;module.exports.server = server; &#xA;Example:&#xA;&#xA;  The code provided here is a recap of How to make nodejs applications modular article. You may need to give it a test drive, as this section highlights an already modularized example. &#xA;&#xA;Testing&#xA;&#xA;Automation is what developers do for a living. Manual testing is tedious, repetitive, and those are two key characteristics of things we love automating. Automated testing is quite intimidating for newbies and veterans alike. Testing tends to be more of an art, the more you practice, the better you hone your craft.&#xA;&#xA;  In the blogosphere, - My node Test Strategy  ~ RSharper Blog. - nodejs testing essentials&#xA;&#xA;BDD versus TDD&#xA;&#xA;Why should we even test&#xA;&#xA;Testing is unanimous within the developers community, the question always is around how to go about testing. &#xA;&#xA;There is a discussion mentioned in the first chapter between @kentbeck, @martinfowler and @dhh that made rounds on social media, blogs and finally as a subject of reflection in the community. When dealing with legacy code, there should be a balance and only adopt tdd as one tool in our toolbox. &#xA;&#xA;In the book we do the following exercise alternative to classic tdd: read, analyze, modify if necessary, rinse and repeat. We cut the bullshit, and get to test whatever needs to be tested, and let nature take its course.&#xA;&#xA;One thing is clear: We cannot guarantee the sanity of a piece of code unless it is tested. The remaining question is on &#34;How&#34; to go about testing. &#xA;&#xA;  There is a summary of the discussions mentioned earlier, titled Is TDD Dead?. In the blogosphere, - BDD-TDD ~ RobotLovesYou Blog. - My node Test Strategy  ~ RSharper Blog - A TDD Approach to Building a Todo API Using nodejs and mongodb ~ SemaphoreCI Community Tutorials &#xA;&#xA;What should be tested &#xA;&#xA;Before we dive into it, lets re-examine pros and cons of automated tests -- in the current case, Unit Tests.&#xA;&#xA;Pros:&#xA;&#xA;Steer release confidence &#xA;Prevents common use case and unexpected bugs&#xA;Help project&#39;s new developers better understand code &#xA;Improves confidence when refactoring code &#xA;Well tested product guarantees improves customer experience &#xA;&#xA;Cons:&#xA;&#xA;Take time to write&#xA;Increase learning curve&#xA;&#xA;At this point, if we agree that the pros outweigh the cons, we can set an ideal of testing everything. Those are features of a product or functions of code. Re-testing large applications manually are daunting, exhausting, and sometimes simply not feasible. &#xA;&#xA;The good way to think about testing is not by thinking in terms of layers(controllers, models, etc.). Layers tend to be bigger. It is better to think in terms of something much smaller like a function(TDD way) or a feature(BDD way).&#xA;&#xA;Brief, every controller/business logic/utility libraries/nodejs servers/routes all features are also set to be tested ahead of release. &#xA;&#xA;  There is an article on this blog that gives more insight on -- How to create good test cases (Case   Feature   Expectations | GivenWhenThen) -- titled &#34;How to write test cases developers will love reading&#34;. In the blogosphere, - Getting started with nodejs and mocha&#xA;&#xA;Choosing the right testing tools&#xA;&#xA;There is no shortage of tools in nodejs community. The problem is analysis paralysis. Whenever the time comes to choose testing tools, there are layers that should be taken into account: test runners, test doubles, reporting, and eventually, if there is any compiler that needs to be added in the mix. &#xA;&#xA;Other than that, there is a list of a few things to consider when choosing a testing framework: - Learning curve - How easy to integrate into project/existing testing frameworks - How long does it take to debug testing code - Choice of the testing framework, and other testing tools consider - How good is documentation - How big is the community, and how good is the library maintained - What is may solve faster(Spies, Mocking, Coverage reports, etc) - Instrumentation and test reporting, just to name a few.&#xA;&#xA;  There are sections dedicated to providing hints and suggestions throughout the book. There is also this article &#34;How to choose the right tools&#34; on this blog that gives a baseline framework to choose, not only for testing frameworks but any tool. Finally, In the blogosphere, - jasmine vs. mocha, chai and sinon. - Evan Hahn has pretty good examples of the use of test doubles in How do I jasmine blog post.  - Getting started with nodejs and jasmine - has some pretty amazing examples, and is simple to start with. - Testing expressjs REST APIs with Mocha&#xA;&#xA;Testing servers&#xA;&#xA;The not-so-obvious part when testing servers is how to simulation of starting and stopping the server. These two operations should not bootstrap dependent servers(database, data-stores) or make side effects(network requests, writing to files) to reduce the risk associated with running an actual server. &#xA;&#xA;  There is a chapter dedicated to testing servers in the book. There is also this article on this blog that can give more insights. In the blogosphere, - How to correctly unit test express server - There is a better code structure organization, that makes it easy to test and get good test coverage on &#34;Testing nodejs with mocha&#34;. - How to correctly unit test express server&#xA;&#xA;Testing modules &#xA;&#xA;Testing modules is not that different from testing a function, or a class. When we start looking at this from this angle, things will be a little easy. &#xA;&#xA;The grain of salt: a module that is not directly a core component of our application, should be left alone and mocked out entirely when possible. This way we keep things isolated. &#xA;&#xA;  There are dedicated sections in every chapter about modularization, as well as a chapter dedicated to testing utility libraries(modules) in the book. There is also an entire series of articles -- a more theoretical: &#34;How to make nodejs applications modular and a more technical: &#34;How to modularize nodejs applications&#34; -- on this blog modularization techniques. In the blogosphere, - Export This: Interface Design Patterns for nodejs Modules Alon Salant, CEO of Good Eggs and nodejs module patterns using simple examples by Darren DeRider - How to modularize your Chat Application&#xA;&#xA;Testing routes&#xA;&#xA;Challenges while testing expressjs Routes&#xA;&#xA;Some of the challenges associated with testing routes are testing authenticated routes, mocking requests, mocking responses as well as testing routes in isolation without a need to spin up a server. When testing routes, it is easy to fall into integration testing trap, either for simplicity or for lack of motivation to dig deeper. &#xA;&#xA;  Integration testing trap is When a developer confuses integration test(or E2E) with unit test, and vice versa. The success of a balanced test coverage identifies sooner the king of tests adequate for a given context, what percentage of each kind of tests.&#xA;&#xA;For a test to be a unit test in route testing context, there will be - Focus to test code block(function, class, etc), not the output of a route - Mock requests to third party systems(Payment Gateway, Email Systems, etc) - Mock database read/write operations - Test worst-case scenario such as missing data and data-structure &#xA; &#xA;  There is a chapter dedicated to testing models in the book. There is also this article &#34;Testing expressjs Routes&#34; on this blog that gives more insight on the subject. In the blogosphere - A TDD approach to building a todo API using nodejs and mongodb - Marcus on supertest ~ Marcus Soft Blog&#xA;&#xA;Testing controllers &#xA;&#xA;When modularizing route handlers, there is a realization that they may also be grouped into a layer of their own, or event classes. In MVC jargon, this layer is also known as the controller layer. &#xA;&#xA;Challenges testing controllers, by no surprise, are the same when testing expressjs route handlers. The controller layer thrives when there is a service layer. Mocking database read/write operations, or service layers, that is not core/critical to validation of the controller&#39;s expectations are some of such challenges. &#xA;&#xA;Mocking controller request/response objects, and when necessary, some middleware functions. &#xA;&#xA;  There is a chapter dedicated to testing controllers in the book. There is also this article Testing nodejs controllers with expressjs framework on this blog that gives more insight on the subject. In the blogosphere, - This article covers Mocking Responses, etc -- How to test express controllers. &#xA;&#xA;Testing services &#xA;&#xA;There are some instances where adding a service layer makes sense. &#xA;&#xA;One of those instances is when an application has a collection of single functions under utility(utils). Chances are some of the functions under the utility umbrella may be related in terms of features, the functionality they offer, or both. Such functions are good to use case to be grouped under a class: service&#xA;&#xA;Another good example is for applications that heavily use the model. Chances are the same functions can be re-used in multiple instances, and fixing an issue involves multiple places to fix as well. When that is the case, such functions can be grouped under one banner, in such a way that an update to one function, gets reflected in every instance where the function has been used.&#xA;&#xA;From these two use cases, the testing service has no one-size fit-all testing strategy. Every case of service should be dealt with depending on the context it is operating in.  &#xA;&#xA;  There is a chapter dedicated to testing services in the book. In the blogosphere, - &#34;Building Structured Backends with nodejs and HexNut&#34; by Francis Stokes ~ aka @fstokesman on Twitter source ...&#xA;&#xA;Testing middleware &#xA;&#xA;The middleware in a sense are hooks that intercept, process and forward the result to the rest of the route in the expressjs (connectjs) jargon. It is by no surprise that testing middleware shares the same challenges as testing route handlers and controllers. &#xA;&#xA;  There is a chapter dedicated to testing middleware in the book. There is also this article &#34;Testing expressjs Middleware&#34; on this blog that gives more insight on the subject. In the blogosphere, - How to test expressjs controllers&#xA;&#xA;Testing asynchronous code&#xA;&#xA;Asynchronous code is a wide subject in nodejs community. Things ranging from regular callbacks, promises, async/await constructs, streams, and event streams(reactive) are all under an asynchronous umbrella.&#xA;&#xA;Challenges associated with asynchronous testing, depending on the use case and context at hand. However, there are striking similarities say, testing testing async/await versus a promise. &#xA;&#xA;When an object is available, it makes sense to get a hold on it, execute assertions once it resolves. That is feasible for promises, streams, async/await construct. However, when the object is some kind of event, then the hold on the object can be used to add a listener and assert once the listener is resolved. &#xA;&#xA;  There are multiple chapters dedicated to testing asynchronous code in the book. There are also multiple article on this blog that gives more insight on the subject such as - &#34;How to stub a stream function&#34; - &#34;How to Stub Promise Function and Mock Resolved Output&#34; - &#34;Testing nodejs streams&#34;. In the blogosphere, - &#xA;&#xA;Testing models&#xA;&#xA;  testing models goes hand in hand with mocking database access functions&#xA;&#xA;Functions that access or change database state can be replaced by spy fakes, custom function replacements capable to supply|emulate similar results as replaced functions. &#xA;&#xA;sinon may not make unanimity, but is a feature-complete battle-tested test double library, amongst many others to choose from.&#xA;&#xA;  There is a chapter dedicated to testing models in the book. There is also this article  on this blog that gives more insight on the subject. In the blogosphere, - Mocking/Stubbing/Spying mongoose models - stubbing mongoose model question and answers on StackOverflow - Mocking database calls by wrapping mongoose with mockgoose&#xA;&#xA;Testing WebSockets&#xA;&#xA;Some of the challenges testing WebSockets can be summarized as trying to simulate: - sending and receiving a message on the WebSocket endpoint. &#xA;&#xA;  There is a chapter dedicated to testing WebSockets in the book. There is also this article on this blog that can give more ideas on how to go about testing WebSocket endpoints -- another one on how to integrate WebSockets with nodejs. Elsewhere in the blogosphere, - Testing socket.io with mocha, should.js and socket.io client - sharing session between expressjs and socket.io&#xA;&#xA;Testing background jobs &#xA;&#xA;The background jobs bring batch processing to the nodejs ecosystem. Background jobs constitute a special use case of asynchronous communication that spans time and processes on which the system is running on. &#xA;&#xA;Testing this kind of complex construct, require distilling the fundamental work done by each function/construct, by focusing on the signal without losing the big picture. It requires quite a paradigm shift(word used with reservation).  &#xA;&#xA;  There is a chapter dedicated to testing background jobs in the book. There is an article Testing nodejs streams on this blog that gives more insight on the subject. In the blogosphere, - Mocking/Stubbing/Spying mongoose models ~ CodeUtopia Blog&#xA;&#xA;Conclusion &#xA;&#xA;Some source code samples came from QA sites such as StackOverflow, hackers gists, Github documentation, developer blogs, and from my personal projects. &#xA;&#xA;There are some aspects of the ecosystem that are not mentioned, not because they are not important, but because mentioning all of them can fit into a book. &#xA;&#xA;In this article, we highlighted what it takes to test various layers, at the same time make a difference between BDD/TDD testing schools. There are additional complimentary materials in the &#34;Testing nodejs applications&#34; book.  &#xA;&#xA;References&#xA;&#xA;Testing nodejs Applications book&#xA;Testing MEAN stack with Mocha ~ The Way of Code&#x9;~ &#34;How to build and test REST with nodejs Express Mocha&#34;&#xA;&#xA;#snippets #nodejs #testing #tdd #bdd]]&gt;</description>
      <content:encoded><![CDATA[<p>This post highlights snapshots on best practices/hacks, to code, test, deploy and to maintain large-scale <code>nodejs</code> apps. It provides big lines on what became a book on <em><a href="https://bit.ly/2ZFJytb">testing <code>nodejs</code> applications</a></em>.</p>

<blockquote><p>If you haven&#39;t yet, read the <a href="./how-to-make-nodejs-application-modular.md">How to make <code>nodejs</code> applications modular</a> article. This article is an overall follow-up.</p></blockquote>

<p>Like some of the articles that came before this one, we are going to focus on a simple question as our north star: <em>What are the most important questions developers have when testing a <code>nodejs</code> application?</em> When possible a quick answer will be provided, else we will point in the right direction where information can be found.</p>

<p><strong><em>In this article we will talk about:</em></strong></p>
<ul><li><a href="./overview-on-testing-nodejs-applications#bdd-versus-tdd">BDD versus TDD</a></li>
<li><a href="./overview-on-testing-nodejs-applications#choosing-the-right-testing-tools">Choosing the right testing tools</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-servers">Testing servers</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-modules">Testing modules</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-routes">Testing routes</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-controllers">Testing controllers</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-services">Testing services</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-middleware">Testing middleware</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-asynchronous-code">Testing asynchronous code</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-models">Testing models</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-websockets">Testing WebSockets</a></li>
<li><a href="./overview-on-testing-nodejs-applications#testing-testing-background-jobs">Testing background jobs</a></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;),
  app = express(),
  server = require(&#39;http&#39;).createServer(app);
//...
require(&#39;./config&#39;);
require(&#39;./utils/mongodb&#39;);
require(&#39;./utils/middleware&#39;)(app);
require(&#39;./routes&#39;)(app);
require(&#39;./realtime&#39;)(app, server)
//...
module.exports.server = server; 
</code></pre>

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

<blockquote><p>The code provided here is a recap of <a href="./how-to-make-nodejs-application-modular.md">How to make <code>nodejs</code> applications modular</a> article. You may need to give it a test drive, as this section highlights an already modularized example.</p></blockquote>

<h2 id="testing" id="testing">Testing</h2>

<p>Automation is what developers do for a living. Manual testing is tedious, repetitive, and those are two key characteristics of things we love automating. Automated testing is quite intimidating for newbies and veterans alike. Testing tends to be more of an art, the more you practice, the better you hone your craft.</p>

<blockquote><p>In the blogosphere, – My <code>node</code> Test Strategy  ~ <a href="https://remysharp.com/2015/12/14/my-node-test-strategy">RSharper Blog</a>. – <a href="https://fredkschott.com/post/2014/05/nodejs-testing-essentials/"><code>nodejs</code> testing essentials</a></p></blockquote>

<h2 id="bdd-versus-tdd" id="bdd-versus-tdd">BDD versus TDD</h2>

<p><em>Why should we even test</em></p>

<p>Testing is unanimous within the developers community, the question always is around <em>how</em> to go about testing.</p>

<p>There is a discussion mentioned in the first chapter between @kentbeck, @martinfowler and @dhh that made rounds on social media, blogs and finally as a subject of reflection in the community. When dealing with legacy code, there should be a balance and only adopt <code>tdd</code> as one tool in our toolbox.</p>

<p>In the book we do the following exercise alternative to classic <code>tdd</code>: <strong><em>read, analyze, modify if necessary, rinse and repeat</em></strong>. We cut the bullshit, and get to test whatever needs to be tested, and let nature take its course.</p>

<p>One thing is clear: We cannot guarantee the sanity of a piece of code unless it is tested. The remaining question is on <em>“How”</em> to go about testing.</p>

<blockquote><p>There is a summary of the discussions mentioned earlier, titled <a href="https://martinfowler.com/articles/is-tdd-dead/">Is TDD Dead?</a>. In the blogosphere, – BDD-TDD ~ <a href="https://www.robotlovesyou.com/bdd-tdd/">RobotLovesYou Blog</a>. – My <code>node</code> Test Strategy  ~ <a href="https://remysharp.com/2015/12/14/my-node-test-strategy">RSharper Blog</a> – 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></p></blockquote>

<h2 id="what-should-be-tested" id="what-should-be-tested">What should be tested</h2>

<p>Before we dive into it, lets re-examine <strong><em>pros</em></strong> and <strong>cons</strong> of automated tests — in the current case, Unit Tests.</p>

<p><strong>Pros</strong>:</p>
<ul><li>Steer release confidence</li>
<li>Prevents common use case and unexpected bugs</li>
<li>Help project&#39;s new developers better understand code</li>
<li>Improves confidence when refactoring code</li>
<li>Well tested product guarantees improves customer experience</li></ul>

<p><strong>Cons</strong>:</p>
<ul><li>Take time to write</li>
<li>Increase learning curve</li></ul>

<p>At this point, if we agree that the pros outweigh the cons, we can set an ideal of testing everything. Those are features of a product or functions of code. Re-testing large applications manually are daunting, exhausting, and sometimes simply not feasible.</p>

<p>The good way to think about testing is not by thinking in terms of layers(controllers, models, etc.). Layers tend to be bigger. It is better to think in terms of something much smaller like a function(TDD way) or a feature(BDD way).</p>

<p>Brief, every controller/business logic/utility libraries/<code>nodejs</code> servers/routes all features are also set to be tested ahead of release.</p>

<blockquote><p>There is an article on this blog that gives more insight on — How to create good test cases (Case &gt; Feature &gt; Expectations | GivenWhenThen) — titled <a href="how-to-write-test-cases-developers-will-love-reading">“How to write test cases developers will love reading”</a>. In the blogosphere, – <a href="https://semaphoreci.com/community/tutorials/getting-started-with-node-js-and-mocha">Getting started with <code>nodejs</code> and <code>mocha</code></a></p></blockquote>

<h2 id="choosing-the-right-testing-tools" id="choosing-the-right-testing-tools">Choosing the right testing tools</h2>

<p>There is no shortage of tools in <code>nodejs</code> community. The problem is <em>analysis paralysis</em>. Whenever the time comes to choose testing tools, there are layers that should be taken into account: test runners, test doubles, reporting, and eventually, if there is any compiler that needs to be added in the mix.</p>

<p>Other than that, there is a list of a few things to consider when choosing a testing framework: – Learning curve – How easy to integrate into project/existing testing frameworks – How long does it take to debug testing code – Choice of the testing framework, and other testing tools consider – How good is documentation – How big is the community, and how good is the library maintained – What is may solve faster(Spies, Mocking, Coverage reports, etc) – Instrumentation and test reporting, just to name a few.</p>

<blockquote><p>There are sections dedicated to providing hints and suggestions throughout the book. There is also this article <a href="./how-to-choose-the-right-tools">“How to choose the right tools”</a> on this blog that gives a baseline framework to choose, not only for testing frameworks but any tool. Finally, In the blogosphere, – <a href="https://thejsguy.com/2015/01/12/jasmine-vs-mocha-chai-and-sinon.html"><code>jasmine</code> vs. <code>mocha</code>, <code>chai</code> and <code>sinon</code></a>. – Evan Hahn has pretty good examples of the use of test doubles in <a href="https://evanhahn.com/how-do-i-jasmine/">How do I <code>jasmine</code></a> blog post.  – <a href="https://semaphoreci.com/community/tutorials/getting-started-with-node-js-and-jasmine">Getting started with <code>nodejs</code> and <code>jasmine</code></a> – has some pretty amazing examples, and is simple to start with. – <a href="https://51elliot.blogspot.ca/2013/08/testing-expressjs-rest-api-with-mocha.html">Testing <code>expressjs</code> REST APIs with Mocha</a></p></blockquote>

<h2 id="testing-servers" id="testing-servers">Testing servers</h2>

<p>The not-so-obvious part when testing servers is how to simulation of starting and stopping the server. These two operations should not bootstrap dependent servers(database, data-stores) or make side effects(network requests, writing to files) to reduce the risk associated with running an actual server.</p>

<blockquote><p>There is a chapter dedicated to testing servers in the book. There is also this [article on this blog that can give more insights](). In the blogosphere, – How to correctly unit test express server – There is a better code structure organization, that makes it easy to test and get good test coverage on <a href="https://brianstoner.com/blog/testing-in-nodejs-with-mocha/">“Testing <code>nodejs</code> with mocha”</a>. – <a href="https://glebbahmutov.com/blog/how-to-correctly-unit-test-express-server/">How to correctly unit test express server</a></p></blockquote>

<h2 id="testing-modules" id="testing-modules">Testing modules</h2>

<p>Testing modules is not that different from testing a function, or a class. When we start looking at this from this angle, things will be a little easy.</p>

<p>The grain of salt: a module that is not directly a core component of our application, should be left alone and mocked out entirely when possible. This way we keep things isolated.</p>

<blockquote><p>There are dedicated sections in every chapter about modularization, as well as a chapter dedicated to testing utility libraries(modules) in the book. There is also an entire series of articles — a more theoretical: <a href="./how-to-make-nodejs-applications-modular">“How to make <code>nodejs</code> applications modular</a> and a more technical: <a href="./modularizing-nodejs-applications">“How to modularize <code>nodejs</code> applications”</a> — on this blog modularization techniques. In the blogosphere, – <a href="http://bites.goodeggs.com/posts/export-this/">Export This: Interface Design Patterns for <code>nodejs</code> Modules</a> Alon Salant, CEO of Good Eggs and <a href="https://darrenderidder.github.io/talks/ModulePatterns/#/"><code>nodejs</code> module patterns using simple examples</a> by <a href="https://twitter.com/73rhodes">Darren DeRider</a> – <a href="https://medium.com/philosophie-is-thinking/modularize-your-chat-app-or-how-to-write-a-node-js-express-app-in-more-than-one-file-bfae2d6b69df#.hfb4r6z3i">How to modularize your Chat Application</a></p></blockquote>

<h2 id="testing-routes" id="testing-routes">Testing routes</h2>

<p><em>Challenges while testing <code>expressjs</code> Routes</em></p>

<p>Some of the challenges associated with testing routes are <em>testing authenticated routes</em>, <em>mocking requests</em>, <em>mocking responses</em> as well as <em>testing routes in isolation without a need to spin up a server</em>. When testing routes, it is easy to fall into <em>integration testing trap</em>, either for simplicity or for lack of motivation to dig deeper.</p>

<blockquote><p>Integration testing trap is <em>When a developer confuses integration test(or E2E) with unit test, and vice versa</em>. The success of a balanced test coverage identifies sooner the king of tests adequate for a given context, what percentage of each kind of tests.</p></blockquote>

<p>For a test to be a unit test in route testing context, there will be – Focus to test code block(function, class, etc), not the output of a route – Mock requests to third party systems(Payment Gateway, Email Systems, etc) – Mock database read/write operations – Test worst-case scenario such as missing data and data-structure</p>

<blockquote><p>There is a chapter dedicated to testing models in the book. There is also this article <a href="./testing-expressjs-routes">“Testing <code>expressjs</code> Routes”</a> on this blog that gives more insight on the subject. In the blogosphere – <a href="https://semaphoreci.com/community/tutorials/a-tdd-approach-to-building-a-todo-api-using-node-js-and-mongodb">A TDD approach to building a todo API using <code>nodejs</code> and <code>mongodb</code></a> – Marcus on <code>supertest</code> ~ <a href="https://www.marcusoft.net/2014/02/mnb-supertest.html">Marcus Soft Blog</a></p></blockquote>

<h2 id="testing-controllers" id="testing-controllers">Testing controllers</h2>

<p>When modularizing route handlers, there is a realization that they may also be grouped into a layer of their own, or event classes. In MVC jargon, this layer is also known as the controller layer.</p>

<p>Challenges testing controllers, by no surprise, are the same when testing <code>expressjs</code> route handlers. The controller layer thrives when there is a service layer. Mocking database read/write operations, or service layers, that is not core/critical to validation of the controller&#39;s expectations are some of such challenges.</p>

<p>Mocking controller request/response objects, and when necessary, some middleware functions.</p>

<blockquote><p>There is a chapter dedicated to testing controllers in the book. There is also this article <a href="./testing-nodejs-controllers-with-expressjs-framework">Testing <code>nodejs</code> controllers with <code>expressjs</code> framework</a> on this blog that gives more insight on the subject. In the blogosphere, – This article covers Mocking Responses, etc — <a href="https://www.terlici.com/2015/09/21/node-express-controller-testing.html">How to test express controllers</a>.</p></blockquote>

<h2 id="testing-services" id="testing-services">Testing services</h2>

<p>There are some instances where adding a service layer makes sense.</p>

<p>One of those instances is when an application has a collection of single functions under utility(utils). Chances are some of the functions under the utility umbrella may be related in terms of features, the functionality they offer, or both. Such functions are good to use case to be grouped under a class: service</p>

<p>Another good example is for applications that heavily use the model. Chances are the same functions can be re-used in multiple instances, and fixing an issue involves multiple places to fix as well. When that is the case, such functions can be grouped under one banner, in such a way that an update to one function, gets reflected in every instance where the function has been used.</p>

<p>From these two use cases, the testing service has no <em>one-size fit-all</em> testing strategy. Every case of service should be dealt with depending on the context it is operating in.</p>

<blockquote><p>There is a chapter dedicated to testing services in the book. In the blogosphere, – <em>“Building Structured Backends with <code>nodejs</code> and HexNut”</em> by Francis Stokes ~ aka @fstokesman on Twitter <em><a href="https://itnext.io/build-structured-web-socket-backends-in-node-with-hexnut-1d505c9c30b0">source ...</a></em></p></blockquote>

<h2 id="testing-middleware" id="testing-middleware">Testing middleware</h2>

<p>The middleware in a sense are hooks that intercept, process and forward the result to the rest of the route in the <code>expressjs</code> (<code>connectjs</code>) jargon. It is by no surprise that testing middleware shares the same challenges as testing route handlers and controllers.</p>

<blockquote><p>There is a chapter dedicated to testing middleware in the book. There is also this article <a href="./testing-expressjs-middleware">“Testing <code>expressjs</code> Middleware”</a> on this blog that gives more insight on the subject. In the blogosphere, – <a href="https://www.terlici.com/2015/09/21/node-expressjs-controller-testing.html">How to test <code>expressjs</code> controllers</a></p></blockquote>

<h2 id="testing-asynchronous-code" id="testing-asynchronous-code">Testing asynchronous code</h2>

<p>Asynchronous code is a wide subject in <code>nodejs</code> community. Things ranging from regular callbacks, promises, async/await constructs, streams, and event streams(reactive) are all under an asynchronous umbrella.</p>

<p>Challenges associated with asynchronous testing, depending on the use case and context at hand. However, there are striking similarities say, testing testing <code>async/await</code> versus a promise.</p>

<p>When an object is available, it makes sense to get a hold on it, execute assertions once it resolves. That is feasible for promises, streams, async/await construct. However, when the object is some kind of event, then the hold on the object can be used to add a listener and assert once the listener is resolved.</p>

<blockquote><p>There are multiple chapters dedicated to testing asynchronous code in the book. There are also multiple article on this blog that gives more insight on the subject such as – <a href="./how-to-stub-a-stream-function">“How to stub a <code>stream</code> function”</a> – <a href="./how-to-stub-promise-function-and-mock-resolved-output">“How to Stub Promise Function and Mock Resolved Output”</a> – <a href="./testing-nodejs-streams">“Testing <code>nodejs</code> streams”</a>. In the blogosphere, – []()</p></blockquote>

<h2 id="testing-models" id="testing-models">Testing models</h2>

<blockquote><p>testing models goes hand in hand with mocking database access functions</p></blockquote>

<p>Functions that access or change database state can be replaced by spy fakes, custom function replacements capable to supply|emulate similar results as replaced functions.</p>

<p><code>sinon</code> may not make unanimity, but is a feature-complete battle-tested test double library, amongst many others to choose from.</p>

<blockquote><p>There is a chapter dedicated to testing models in the book. There is also this article []() on this blog that gives more insight on the subject. In the blogosphere, – <a href="https://codeutopia.net/blog/2016/06/10/mongoose-models-and-unit-tests-the-definitive-guide/">Mocking/Stubbing/Spying mongoose models</a> – <a href="https://stackoverflow.com/a/11567859/132610">stubbing mongoose model question and answers on StackOverflow</a> – Mocking database calls by wrapping <code>mongoose</code> with <a href="https://github.com/mfncooper/mockery"><code>mockgoose</code></a></p></blockquote>

<h2 id="testing-websockets" id="testing-websockets">Testing WebSockets</h2>

<p>Some of the challenges testing WebSockets can be summarized as trying to simulate: – sending and receiving a message on the <code>WebSocket</code> endpoint.</p>

<blockquote><p>There is a chapter dedicated to testing WebSockets in the book. There is also this <a href="./testing-nodejs-websocket-endpoints">article on this blog that can give more ideas on how to go about testing WebSocket endpoints</a> — another one on <a href="./integration-of-websockets-in-nodejs-application">how to integrate WebSockets with <code>nodejs</code></a>. Elsewhere in the blogosphere, – <a href="https://liamkaufman.com/blog/2012/01/28/testing-socketio-with-mocha-should-and-socketio-client/">Testing <code>socket.io</code> with <code>mocha</code>, <code>should.js</code> and <code>socket.io</code> client</a> – <a href="https://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x">sharing session between <code>expressjs</code> and <code>socket.io</code></a></p></blockquote>

<h2 id="testing-background-jobs" id="testing-background-jobs">Testing background jobs</h2>

<p>The background jobs bring batch processing to the <code>nodejs</code> ecosystem. Background jobs constitute a special use case of asynchronous communication that spans time and processes on which the system is running on.</p>

<p>Testing this kind of complex construct, require distilling the fundamental work done by each function/construct, by focusing on the signal without losing the big picture. It requires quite a paradigm shift(<em>word used with reservation</em>).</p>

<blockquote><p>There is a chapter dedicated to testing background jobs in the book. There is an article <a href="./testing-nodejs-streams">Testing <code>nodejs</code> streams</a> on this blog that gives more insight on the subject. In the blogosphere, – Mocking/Stubbing/Spying <code>mongoose</code> models ~ <a href="https://codeutopia.net/blog/2016/06/10/mongoose-models-and-unit-tests-the-definitive-guide/">CodeUtopia Blog</a></p></blockquote>

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

<p>Some source code samples came from QA sites such as StackOverflow, hackers <em>gists</em>, Github documentation, developer blogs, and from my personal projects.</p>

<p>There are some aspects of the ecosystem that are not mentioned, not because they are not important, but because mentioning all of them can fit into a book.</p>

<p>In this article, we highlighted what it takes to test various layers, at the same time make a difference between BDD/TDD testing schools. 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>Testing MEAN stack with Mocha ~ <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>    ~ “How to build and test REST with <code>nodejs</code> Express Mocha”</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:nodejs" class="hashtag"><span>#</span><span class="p-category">nodejs</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:tdd" class="hashtag"><span>#</span><span class="p-category">tdd</span></a> <a href="https://getsimple.works/tag:bdd" class="hashtag"><span>#</span><span class="p-category">bdd</span></a></p>
]]></content:encoded>
      <guid>https://getsimple.works/overview-on-testing-nodejs-applications</guid>
      <pubDate>Thu, 17 Jun 2021 04:34:31 +0000</pubDate>
    </item>
  </channel>
</rss>