<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Serguey Arellano Martínez on Medium]]></title>
        <description><![CDATA[Stories by Serguey Arellano Martínez on Medium]]></description>
        <link>https://medium.com/@sergueymartinez?source=rss-4171bb0fc143------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VC_aTL7l1sHvtjdJ</url>
            <title>Stories by Serguey Arellano Martínez on Medium</title>
            <link>https://medium.com/@sergueymartinez?source=rss-4171bb0fc143------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 13:47:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergueymartinez/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TDD, BDD in Javascript World. Node. Refactoring and notes. 5/5]]></title>
            <link>https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-refactoring-and-notes-5-5-17db9d0ecea4?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/17db9d0ecea4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[cucumber]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Fri, 28 May 2021 18:41:27 GMT</pubDate>
            <atom:updated>2021-05-28T18:41:27.546Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-writing-code-4-5-afb96c1e5dda">Part 4</a> we implemented the necessary code to satisfy the assertions we made in the acceptance criteria which we stipulated with the customer/PO and PM for that specific feature.</p><p>If you are lost with code/files, you can always check the repo to see the <a href="https://github.com/sergueyarellano/tddpractice">complete project</a></p><p>In Part 5 you will learn:</p><ul><li>the importance of decision making in BDD, TDD projects</li><li>Possible problems and how to approach them</li><li>How to approach a refactor</li><li>Execute your integration tests against different environments</li></ul><h3>There will be obstacles</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjEfRgljSYTCm01XF70EPA.jpeg" /><figcaption>sometimes it’s not even easy when there are no obstacles — Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6282cd891a5d0aad99d65de6f17f6869/href">https://medium.com/media/6282cd891a5d0aad99d65de6f17f6869/href</a></iframe><p>Another question that the PM can ask you is how granular the features should be. In my opinion, developers have to try to understand the business value or how the features and scenarios are presented. If they are presented in a way that would make the test very complex, you should talk to your PM to split those scenarios/features in smaller cases. Only experience can tell you what is the best approach.</p><p>It is a process to adapt to BDD, TDD. The benefits are huge, but there are going to be obstacles in our way. It could be inexperience from both business and dev parts, not understanding how to write features, or something else entirely.</p><blockquote><em>Try to keep it simple and always do what is going to help you sleep at night</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rl_YqD4iDIlVPNvtZvzOLw.jpeg" /><figcaption>there is a K.I.S.S. behind that H.E.A.R.T, or that’s what I T.H.I.N.K. — Photo by <a href="https://www.pexels.com/@natalie-320378?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Natalie</a></figcaption></figure><p>It is also a plus to have mentors that help you or the company on their way.</p><h3>About Refactoring</h3><p>Rule of thumb about refactoring</p><blockquote><em>Whenever you need to attempt a refactor make sure you are pretty well covered with tests</em></blockquote><p>A rookie mistake is to approach a refactor without tests.</p><p>How do you ensure that doing modifications to a component or components does not affect the outcome? With manual testing? Logging a couple of things?</p><p>If you are a senior developer, you know that you have to do the right thing. In my opinion, do it with elegance and some philosophy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_s8lHOU9Bgqaw4GgHY0Zw.jpeg" /><figcaption>it’s hard to be handsome, elegant and humble — Photo by <a href="https://www.pexels.com/@cottonbro">cottonbro</a></figcaption></figure><blockquote><em>I test my code because I feel responsible for what I write</em></blockquote><p>Whenever you ask yourself if you should do a test or not</p><blockquote><em>do what is going to help you sleep at night</em></blockquote><p>With that said let’s see what can we refactor in our code.</p><h3>Identify patterns</h3><p>If we take a look at our code, we can see this pattern again and again, repeated:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9392627ca22c59981c91b12b93f1c196/href">https://medium.com/media/9392627ca22c59981c91b12b93f1c196/href</a></iframe><p>Also, the tests we designed due to that were like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88e3f448991dc741a846608da5de1543/href">https://medium.com/media/88e3f448991dc741a846608da5de1543/href</a></iframe><p>the problem here is that we have to provide an entire payload structure, but we really don’t need to do that if we create an abstraction like this:</p><pre>setWith(&#39;my.path&#39;, applyFilters(filters))</pre><p>setWith :: (String, Array -&gt; Array ) -&gt; Payload -&gt; Payload</p><p>setWith has to return a function that takes a Payload type and returns the same type to comply with pipe rules</p><p>applyFilters :: Array -&gt; Array -&gt; Array</p><p>applyFilters takes an array of filters and returns a function that takes an array of values, process them applying the filters and returns the result array</p><p>The important abstraction is setWith. We could use it as a tool that gets a value and a function, and applies the function to the value.</p><p>Another example here:</p><pre>setWith(&#39;event.body&#39;, JSON.parse)</pre><p>The result will be a payload with event.body parsed for that example</p><p>Let’s design a test for setWith</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a493704b3f94a941cdf3de7220aef69/href">https://medium.com/media/8a493704b3f94a941cdf3de7220aef69/href</a></iframe><p>If we had passed an identity function instead of JSON.parse the implementation to make that test pass would be:</p><pre>function setWith (path, modifier) {<br>  return payload =&gt; payload<br>}</pre><p>Notice that the test can trick you sometimes. Passing the identity does not make sure that you have to apply it to pass the test. That is why we passed another function like JSON.parse. Nevertheless, if we pass the identity function it has to work too!</p><p>The code to pass the test is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f30e32cbcdd2f8fbbe5e0bb78dba5d59/href">https://medium.com/media/f30e32cbcdd2f8fbbe5e0bb78dba5d59/href</a></iframe><p>Powerful abstraction right?</p><p>It is now time for you to try to refactor the code with this abstraction. Fix the tests accordingly.</p><p>The endpoint should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c100b100c55d079dcdc45b85aedfec4/href">https://medium.com/media/6c100b100c55d079dcdc45b85aedfec4/href</a></iframe><p>Make the test pass and remove filterResponse function and tests after the integration test passes. As you can see, it is a clean process when you <strong>stand on the shoulders of giants</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27d06f83a1194df1929c3e1064a8519a/href">https://medium.com/media/27d06f83a1194df1929c3e1064a8519a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_A5uWKlQ2CTjRdHeFqYH8A.jpeg" /><figcaption>giants doing some testing — Photo by <a href="https://www.pexels.com/@bert-6926305?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Bert</a></figcaption></figure><h3>Making abstractions might not be the best thing</h3><p>Compare the two lines below.</p><pre>setWith(&#39;data.mappedResponse&#39;, applyFilters(config.filters))<br>filterResponse</pre><ul><li>applyFilters has a cleaner signature in my opinion, but it needs setWith as an adapter.</li><li>setWith can be reused for a lot of functions</li><li>filterResponse is simpler but has more magic underneath.</li></ul><p>This is something that you should debate with your team. What would you do?</p><h3>BDD and environments</h3><p>Our case just contemplates a development environment, but how hard would it be to refactor our BDD tests to be able to run in different environments?</p><p>Easy, use environment variables:</p><p>steps/generic.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb6f7c34f18ab2d5b21c0fdc136b78b1/href">https://medium.com/media/fb6f7c34f18ab2d5b21c0fdc136b78b1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMuuDZGOSAHbFgbw7jWrFg.jpeg" /><figcaption>Not to be confused with evironment variabulbs — Photo by <a href="https://www.pexels.com/@singkham-178541?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Singkham</a></figcaption></figure><p>Easy right? Now we just need to change the script in package and pass HOST=http://localhost:3000 or the domain pointing to production. There are several tools like dotenv that can help you here. Remember not to abuse this.</p><blockquote><em>Adapting your production code to environment variables or adding branching is an anti-pattern and should be avoided.</em></blockquote><p>You can do the same exercise for our express app. Remember to spawn the child process passing the required environment variable.</p><p>Merge from lodash can help with that.</p><pre>const ps = spawn(server.command, server.args)<br>{ env: merge(process.env, {HOST_EXTERNAL: &#39;http://localhost:3010&#39; })</pre><h3>Summary</h3><p>Making abstractions is something that you should discuss with your teammates. Try to always maintain readability and keep a declarative style.</p><p>Identify patterns repeating again and again, but don’t be too eager to make the abstraction too soon.</p><p>Refactoring should be made replacing small parts one by one and the code should have a good coverage already. New parts or abstractions should be implemented using TDD if new functions are added in the process to satisfy the refactor.</p><p>Using environment variables multiply the value of BDD, since you can execute your tests against different environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17db9d0ecea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD, BDD in Javascript World. Node. Writing code. 4/5]]></title>
            <link>https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-writing-code-4-5-afb96c1e5dda?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/afb96c1e5dda</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cucumber]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Fri, 28 May 2021 17:59:44 GMT</pubDate>
            <atom:updated>2021-05-28T18:44:20.429Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-writing-cucumber-features-3-5-bcd7fffac0c7">Part 3</a> we got our first feature and implemented its steps in cucumber. We did everything using TDD as part of our BDD process.</p><p>In Part four we will try to apply TDD to produce our production code.</p><p>If you are lost with code/files, you can always check the repo to see the <a href="https://github.com/sergueyarellano/tddpractice">complete project</a></p><p>What you will learn:</p><ul><li>Use of cucumber hooks to prepare the environment</li><li>Spawn processes in Node JS</li><li>Use of BDD and TDD as a workflow</li><li>Functional patterns</li><li>The “wrong first approach”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhsBHDSTunlZdLJ7RDui5Q.jpeg" /><figcaption>we both agree that cucumber is great — Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a></figcaption></figure><h3>Start stubs with cucumber hooks</h3><p>First, let’s analyze the feature we got.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/968ffe38bb8b37efbcc3f97a528c8a5e/href">https://medium.com/media/968ffe38bb8b37efbcc3f97a528c8a5e/href</a></iframe><p>First let’s create a server. That server must have an endpoint called /stores that accepts GET requests.</p><p>app/server.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e33cc0ddc30690c477f181333136a12b/href">https://medium.com/media/e33cc0ddc30690c477f181333136a12b/href</a></iframe><p>Now we need to start this server automatically whenever we execute our integration test. We will use cucumber hooks for that. It is also important to kill every process that we started after all test are executed. We will use another hook to do that. Follow along with me in the next piece of code:</p><p>hooks.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ab51c305894778c9dfc45f931aece19/href">https://medium.com/media/3ab51c305894778c9dfc45f931aece19/href</a></iframe><p>As you can see, integration tests requires a little bit more preparation. Why, you ask? Think about what integration means. We are not testing atomic parts of our program, we are going out of that loop and testing the interconnection between larger pieces. Sounds scary, but the rewards are high. You can now present this tests to the customer to sign off when the feature is completed. See it as proof, as acceptance criteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQLTVfmS-tTHKdkmIQvD9w.jpeg" /><figcaption>atomic parts of one of my programs — Photo by <a href="https://www.pexels.com/@tara-winstead?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Tara Winstead</a></figcaption></figure><p>Well, if you were able to correctly start and halt the server using the hooks, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/0*z5sEIY_oMXlhRkFn.png" /></figure><p>We can see that the first assertion (status code) passed, but the second about validating the interface of the response crashed. And that is totally fine, our server is returning a hello world message for now!</p><p>Now it is time to start implementing the endpoint. Here is an idea with the nice pipe pattern I mentioned in Part one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84265defabbb6bbdef8017bd523f0386/href">https://medium.com/media/84265defabbb6bbdef8017bd523f0386/href</a></iframe><p>I always start writing how I would like to use an API, it is really important to stay declarative in this part. This particular endpoint is serving as a middleware that will call a third party API (or more in the future) and will process the response from the upstream to return a formatted one to the final user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*xpHlpk_OEyKcD1lm.png" /></figure><pre>/* <br>    Map incoming body to what we need to make the request<br>    to the third party<br>    */<br>    composeRequest <br>    makeRequest,<br>    /* Map upstream&#39;s response to what we are returning to the user*/<br>    composeResponse</pre><h3>Creating the pipe function</h3><p>I often talk about composition and pipe with my friends at work, I always find it helpful for this kind of problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUYI0BTVe2_WBPx6ac9NKw.jpeg" /><figcaption>My friends ask me if I also know other functions that are not pipe… mmm naah — Photo by <a href="https://www.pexels.com/@kateryna-babaieva-1423213?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Kateryna Babaieva</a></figcaption></figure><p>I recommend to use the pipe function from a library that has tested the function already, but for the sake of clarity, let’s write it ourselves:</p><p>tools.test.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42261b464aa8dc479768df5f74cd19d8/href">https://medium.com/media/42261b464aa8dc479768df5f74cd19d8/href</a></iframe><p>The test will fail, let’s satisfy the first assertion.</p><p>tools.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e0f44656c4a9a27c5951c7b21fb2752/href">https://medium.com/media/3e0f44656c4a9a27c5951c7b21fb2752/href</a></iframe><p>and the signature is:</p><p>pipe :: fn -&gt; number -&gt; number</p><p>Higher order functions, fancy stuff? Maybe, but very powerful.</p><p>It reads:</p><blockquote><em>pipe takes a function and returns another function that takes a number and returns a number</em></blockquote><p>But the real pipe does not have that signature! Imagine that we could only use pipe passing only one function. What a waste!</p><p>tools.test.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bd582f982def41f98f7ea145fc8830d/href">https://medium.com/media/9bd582f982def41f98f7ea145fc8830d/href</a></iframe><p>This test will pass, but it is a false positive because pipe is only executing the first identity function. You have to be aware of these kind of FALSE POSITIVES when you complete TDD functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc4c4ee7981d12cea5528c2c63a3fe1d/href">https://medium.com/media/cc4c4ee7981d12cea5528c2c63a3fe1d/href</a></iframe><p>So with pipe, it is just a matter of iterating through the functions we pass and keep applying the output to the current function that the previous functions produced. The signature for our pipe is:</p><p>pipe :: ([any -&gt; any]) -&gt; any -&gt; any</p><p>We could keep adding tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75b6c4ef64977549d956ee606a6e1b76/href">https://medium.com/media/75b6c4ef64977549d956ee606a6e1b76/href</a></iframe><p>There are some rules that pipe should comply with like composition.</p><p>Try to figure out with testing first how to design the async version of pipe. What would be the signature now for pipe? would it change at all?</p><p>Well, here you have some help. This would be async pipe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9290a8f4ca99213cdd76d70fd93e1f5/href">https://medium.com/media/f9290a8f4ca99213cdd76d70fd93e1f5/href</a></iframe><p>pipe :: [Any -&gt; Any] -&gt; Any -&gt; Promise</p><p>That means that every step function has to still comply with same input, same output BUT those values can be wrapped in a Promise object. This is interesting because pipe will unwrap and wrap those values without you even noticing. It is also more flexible, because now we can mix sync and async functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99ed360610db8626d27e085c63dae538/href">https://medium.com/media/99ed360610db8626d27e085c63dae538/href</a></iframe><p>If you wanted to know what a monad is, there you go! Now we have a system that wraps and unwraps values, map over values, and is flexible and composable. A Promise looks already like a monadic value, and it also has a then method that looks really similar to a map method if you think about it.</p><h3>Use pipe in the middleware code</h3><p>Our middleware now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97cfdcbdfd1f54903278f4de1e6a7e5/href">https://medium.com/media/c97cfdcbdfd1f54903278f4de1e6a7e5/href</a></iframe><p>We imported pipe and bodyParser just to have easier access to the body of incoming POST, PUT... .</p><p>Let’s modify pipe&#39;s input and create a structure like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6aaf629ddb5906e57c28f93a65769e5/href">https://medium.com/media/f6aaf629ddb5906e57c28f93a65769e5/href</a></iframe><p>Even better, create a factory function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a75d4d6661d9f65c4a4b50d5124d0406/href">https://medium.com/media/a75d4d6661d9f65c4a4b50d5124d0406/href</a></iframe><p>Two things to note here:</p><ul><li>The name lift is just a fancy functional way to call this function, but in fact, we are kind of &quot;lifting&quot; the type here to a type structure that we are going to maintain all along the pipe flow. We will refer to the structure that we just created as &quot;lifted type&quot; or &quot;payload&quot;.</li><li>We did not start with a test because there is no need to test a simple factory function. Trying to achieve 100% coverage is just not focusing where you need to focus.</li></ul><p>We can move now the lift function to tools.js</p><p>I know it looks like a lot of preparation, but look at our first /stores endpoint, it is looking good and loosely coupled, structured and composable.</p><h3>TDD composeRequest</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clwN5JPRhpf5apy3wvTqLQ.jpeg" /><figcaption>request or “gimme da thing” — Photo by <a href="https://www.pexels.com/@louis-965146?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Louis</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e42dfc7d37b08cceeff5c52a9143285/href">https://medium.com/media/0e42dfc7d37b08cceeff5c52a9143285/href</a></iframe><p>tools.test.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdf8071b6bf2d53a5a772126f65a544b/href">https://medium.com/media/cdf8071b6bf2d53a5a772126f65a544b/href</a></iframe><p>composeRequest is a function that will create the options to be used by the next step to make the request. Its signature accepts the type Payload and should return the type Payload because every step function has to comply with that rule.</p><p>Watch the test fail, then implement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56c94d4d71c3812c006ad8eef1bd9ff0/href">https://medium.com/media/56c94d4d71c3812c006ad8eef1bd9ff0/href</a></iframe><p>The test will pass, but there are some things that we can improve:</p><ul><li>traversing properties with lodash get</li><li>setting properties with lodash set</li><li>clone deep the payload whenever we expect to mutate it to avoid side-effects</li><li>abstract setters and getters and create simpler functions</li></ul><p>Ok, but how can we make sure there are no mutations when we test?</p><blockquote><em>deep freezing my friend.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJqfcd_UirK-iXiDe0n2Ow.jpeg" /><figcaption>it’s frozen as my objects or as my washroom at night — Photo by <a href="https://www.pexels.com/@trvlust?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Brady Knoll</a></figcaption></figure><pre>$ npm i -S lodash.get lodash.set lodash.clonedeep<br>$ npm i -D deep-freeze</pre><p>tools.test.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6220fa8f74eb14fa5d6b1fa530154091/href">https://medium.com/media/6220fa8f74eb14fa5d6b1fa530154091/href</a></iframe><p>The test will fail now. Fix the function to pass the test.</p><p>tools.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be4efdf5330420fccaf6d14587b26e54/href">https://medium.com/media/be4efdf5330420fccaf6d14587b26e54/href</a></iframe><p>I always recommend the use of deep freezing your objects in your tests to make sure the functions are not producing undesirable side effects.</p><blockquote><em>Can you see the amount of bugs that we are avoiding already with TDD?</em></blockquote><h3>TDD makeRequest ?</h3><p>I wouldn’t TDD this function because it is a side effect, that is why we have to rely on our BDD test to cover this functionality. Also, this is a library we are using that it is already heavily tested, so we don’t want to reinvent the wheel. This is why choosing the right library is very important and the advantage of the JS and node community.</p><p>network.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ccb8116eb96a89b4b5e590fdc061db/href">https://medium.com/media/b1ccb8116eb96a89b4b5e590fdc061db/href</a></iframe><p>Now it is a good idea to crete a sandbox/stub for the third party that we will start automatically every time we execute our integration tests.</p><p>We can use express here to create a stub:</p><p>test/mocks/stub.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08217cded6042c4a6fc49b84a62b219f/href">https://medium.com/media/08217cded6042c4a6fc49b84a62b219f/href</a></iframe><p>The data we are responding with is data that matches the third party structures. Our job after we request the data is to filter, map it, and return it to the costumer if needed. First, remember that we have to start this stub in cucumber hooks in the same way we start our middleware.</p><h3>TDD mapResponse</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqS-k0jI-sE40hl4FfYy2g.jpeg" /><figcaption>you are here, still… — Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a></figcaption></figure><p>At this point our endpoint should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57ef962bb5c0dd7366d33cd886493151/href">https://medium.com/media/57ef962bb5c0dd7366d33cd886493151/href</a></iframe><p>Our next task should be designing mapResponse in a way that with just providing a &quot;contract&quot; with this structure.</p><pre>contract: {<br>      x: &#39;a&#39;,<br>      y: &#39;b&#39;<br>    }</pre><p>and a response of this type:</p><pre>{<br>  a: 1,<br>  b: 2<br>}</pre><p>the result would be:</p><pre>{<br>  x: 1,<br>  y: 2<br>}</pre><p>It should be easy right? there is a package we can install to map keys:</p><p>$ npm i -S lodash.mapkeys</p><p>And our test approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56e730941351afb7f99e90afc7debcac/href">https://medium.com/media/56e730941351afb7f99e90afc7debcac/href</a></iframe><p>Notice that when doing TDD you are always in the trenches, having to decide whether your API provides one contract or another. For mapResponse you can see that we decided to use it as a step in the pipe function and now it has to ingest the whole payload to do a simple mapping. We can feel that maybe it is not aiming in the right direction. In Part 5 we will learn how we can create proper functional abstractions to improve our aiming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5eiCRLsx1_5OSVmCoZcnlw.jpeg" /><figcaption>thinking about part 5 of this series — Photo by <a href="https://www.pexels.com/@mikhail-nilov?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Mikhail Nilov</a></figcaption></figure><p>We decided with the test that mapResponse is going to have to do the following:</p><ul><li>get the contract from a fixed path</li><li>get the response from a fixed path</li><li>iterate over the response if it is an array</li><li>map over every key according to the contract</li></ul><p>Lots of stuff, right? It looks like this function is doing a lot, that is why we should split the problem.</p><p>Let’s create our mapKeys function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/145d302c41ef78163a81c8bc318131ef/href">https://medium.com/media/145d302c41ef78163a81c8bc318131ef/href</a></iframe><p>This test looks more like a ‘cut to the chase’ kind of problem. We will comment or skip the mapResponse test for now, as it looks more like an integration.</p><pre>function mapKeysWith (data, contract) {<br>  return mapKeys(data, function (value, key) {<br>    // get contract key and substitute<br>  })<br>}</pre><p>There is a nice function that we could use from lodash called invert that is a perfect fit. Our contract has a structure that the user understands x, y but for the substitution it would be nicer if we have a better way to access the props.</p><p>npm i -S lodash.invert</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a868a40efbf8f297ec1dfd09475c9d6/href">https://medium.com/media/1a868a40efbf8f297ec1dfd09475c9d6/href</a></iframe><p>Now you have the opportunity to implement other cases. What will happen if input data has null, undefined values. What happens if the contract expects to have some properties in the input, but they are not there? You have to decide the way this function handle those things. Now it’s your turn!</p><h3>Back to mapResponse</h3><p>This is how the test should look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ce3fa891eef101422e768184084d68/href">https://medium.com/media/65ce3fa891eef101422e768184084d68/href</a></iframe><p>Looks neat, but it is a bit of a pain passing large structures to test this function. As I mentioned before, Part 5 will focus on different mental models and abstractions to improve our solutions with smart refactoring. Hang in there, we are making a lot of progress!</p><p>Let’s update our pipe function with our mapResponse component.</p><pre>const responseBody = await pipe(<br>    composeRequest,<br>    makeRequest,<br>    mapResponse<br>  )(lift(config))</pre><p>But mapResponse is returning the entire payload. We need another step that creates the result with this structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57e0e25a913ac521952e729a1d409d1a/href">https://medium.com/media/57e0e25a913ac521952e729a1d409d1a/href</a></iframe><p>As you can see this looks more like an integration test. Our functions might be doing more than one thing at a time. For now, it is a decision we made, so let’s proceed with the implementation for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c7ea65cd89f8954d1696b7c299c2f92/href">https://medium.com/media/7c7ea65cd89f8954d1696b7c299c2f92/href</a></iframe><p>This is a really easy implementation. As for now, you should have noticed that we are repeating some patterns here. What would be your ideas to refactor?</p><h3>Sending back a proper response</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQSlr9DtsfAD54D9Cx4riA.jpeg" /><figcaption>Thank you, your lordship, sir — Photo by <a href="https://www.pexels.com/@brettjordan?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Brett Jordan</a></figcaption></figure><p>Our endpoint should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e69109444aa1218c484d81f4fc8073d7/href">https://medium.com/media/e69109444aa1218c484d81f4fc8073d7/href</a></iframe><p>The configuration looks good. We provided the correct request info and also the contract that will work as an adapter or model to map the response we will receive from the third party.</p><p>Take a look at the BDD test output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*sQYkxw6d2GuosD_i.png" /></figure><p>Amazing, three assertions are passing, but there is some failure in the assertion that checks the structure of every element in body.data, we can log the output and start debugging.</p><p>There is a problem in our mapping. Each element is mapped to this structure.</p><pre>{<br>      undefined: &#39;store&#39;,<br>      type: &#39;dog&#39;,<br>      description: &#39;Nice alternative dog store in downtown Toronto&#39;,<br>      location: &#39;203 King street West&#39;,<br>      distance: 220<br>    },</pre><p>The element comes like this from the third party:</p><pre>{<br>      type: &#39;store&#39;,<br>      class: &#39;dog&#39;,<br>      report: &#39;Nice alternative dog store in downtown Toronto&#39;,<br>      address: &#39;203 King street West&#39;,<br>      range: 220<br>    },</pre><p>Our contract looks like this:</p><pre>contract: {<br>      type: &#39;class&#39;,<br>      description: &#39;report&#39;,<br>      location: &#39;address&#39;,<br>      distance: &#39;range&#39;<br>    }</pre><p>Well, we did not want to use type property from the third party because it is repetitive. This means that we have a bug. The mapper is not skipping properties that do not exist in our contract.</p><h3>One bug?, one test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTAtvHNU4TQqDj2a1-sW0A.jpeg" /><figcaption>This is a rule of thumb. If you find a bug, you need a test. — Photo by <a href="https://www.pexels.com/@olly?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Andrea Piacquadio</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/024a7aec676c22c9ca236a2bc7eb8e2c/href">https://medium.com/media/024a7aec676c22c9ca236a2bc7eb8e2c/href</a></iframe><p>Now it is time for you to implement the solution. If you are creating semantic commits you could write something like:</p><p>fix: remove undefined property generated in mapKeys</p><ul><li>function fixed in related file</li><li>test case added for the fix</li></ul><blockquote><em>Always add tests to your fix commits</em></blockquote><p>Once fixed, our BDD test has one last reason to fail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/0*pwSIRYmPeSrLxrSh.png" /></figure><p>Check the response body once again, we are not filtering stores that are farther than 200. That is why the assertion is failing.</p><p>Okay, a filter step is needed.</p><h3>Filters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iu2SHQN_GQ3m2n7_7nX3Aw.jpeg" /><figcaption>they are proud of their coffee filtering…also intrigued? — Photo by <a href="https://www.pexels.com/@tim-douglas?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Tim Douglas</a></figcaption></figure><p>I have an idea, since we are using a config object for that specific endpoint, we could add something like this that could work perfectly with our solution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0186c34444e231132c6e29d2369f1a/href">https://medium.com/media/5b0186c34444e231132c6e29d2369f1a/href</a></iframe><p>And start with a test for the filterResponse function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b9563d186f8d7c7c1e2a289b30abbe6/href">https://medium.com/media/7b9563d186f8d7c7c1e2a289b30abbe6/href</a></iframe><p>Watch the test fail, then implement the solution so it satisfies the assertion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3b0a074aa593efaf206a64e749ffeca/href">https://medium.com/media/b3b0a074aa593efaf206a64e749ffeca/href</a></iframe><p>Once the unit test passes, let’s see what is going on in our BDD test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*NiqXSncMsNnwKVGG.png" /></figure><h3>Summary</h3><p>We implemented our production code using TDD with the focus on making the BDD test pass. We had to make decisions on the way about how particular modules will be consumed. TDD and functional programming made us structure our code in a loosely coupled manner. We have unit tests and integration tests covering our first feature.</p><p>In <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-refactoring-and-notes-5-5-17db9d0ecea4">Part 5</a> you will see what we will refactor and throw in some new ideas and mental models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afb96c1e5dda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD, BDD in Javascript World. Node. Writing Cucumber features. 3/5]]></title>
            <link>https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-writing-cucumber-features-3-5-bcd7fffac0c7?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd7fffac0c7</guid>
            <category><![CDATA[cucumber]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Wed, 26 May 2021 17:45:06 GMT</pubDate>
            <atom:updated>2021-05-28T18:45:39.280Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-framework-setup-2-5-ece3c0b46ef6">part 2</a> we set our environment. For part 3 let’s talk to our PM and to our customer so we, as a team, can understand what type of features the customer wants to get done. We will use Gherkin as natural language to try and achieve this.</p><p>If you are lost with code/files, you can always check the repo to see the <a href="https://github.com/sergueyarellano/tddpractice">complete project</a></p><p>You will learn:</p><ul><li>Gherkin as a tool to create acceptance criteria</li><li>Importance of communication between customer and PM</li><li>Black box testing or to “stop caring about the implementation”</li><li>Match Gherkin steps with Cucumber JS</li><li>Use TDD to write Validators</li></ul><h3>Writing features</h3><p>The customer needs a backend app that integrates other API’s from third parties, but we need more specificity from the customer. In order to be on the same page, this is what the customer, my PM, and I agreed on doing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06701c57d6dac15eab10b6a342a84ff7/href">https://medium.com/media/06701c57d6dac15eab10b6a342a84ff7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkB5ystx5vo2H5uiPGlfsw.jpeg" /><figcaption>if the customer doesn’t agree you can practice on the floor to combat frustration — photo by <a href="https://www.pexels.com/@pavel-danilyuk?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pavel Danilyuk</a></figcaption></figure><p>As you can see it is very specific and maybe a little bit technical, so somebody could say that you lose readability using tables, but… why not? if you think about it, we need to design a backend, and a backend is always going to be more lower level. With this approach we are going to sleep better at night, and that alone is a very good reason!</p><h3>Step implementation</h3><p>we have some generic steps to implement, here they are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4812d2caa1b13e61d6ecb3ebc67ef95/href">https://medium.com/media/b4812d2caa1b13e61d6ecb3ebc67ef95/href</a></iframe><p>If you check terminal that is executing the watch command you will see that creating the structure of the steps passed the tests. This is because cucumber will only tell that a step failed when inside that step there was an exception throwing.</p><p>Let’s start implementing the steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aee55c3a721fac2dfcbbc52d5c31cfcb/href">https://medium.com/media/aee55c3a721fac2dfcbbc52d5c31cfcb/href</a></iframe><p>For the step that says I make a &quot;GET&quot; request to &quot;stores&quot; we are going to actually make a request to our stores endpoint.</p><p>Firstly, let’s install an http client:</p><p>npm i -S got</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c18f6e33213481db78d32d1ba9ff96fd/href">https://medium.com/media/c18f6e33213481db78d32d1ba9ff96fd/href</a></iframe><p>At this point you should receiev an error like:</p><pre>RequestError: connect ECONNREFUSED 127.0.0.1:3000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTlmX0kC6UiIdMBB_LxVXw.jpeg" /><figcaption>keep calm, we were expecting this — Photo by <a href="https://www.pexels.com/@alex-green?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Alex Green</a></figcaption></figure><p>This is totally normal, because we started testing our endpoint, and it does not exist yet!</p><p>Nevertheless, in BDD we don’t care about implementation details. Let’s keep trying to implement those steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8289f5c0b46cf7ee982783eb4e2289e0/href">https://medium.com/media/8289f5c0b46cf7ee982783eb4e2289e0/href</a></iframe><p>As you can see, using the expected status as a variable is making this step highly reusable for other scenarios.</p><p>For the next step it is better to install a traverser like lodash in order to get access to deep properties:</p><p>npm i -S lodash.get</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0edb95c28565302ec573cbf8f3ed87a6/href">https://medium.com/media/0edb95c28565302ec573cbf8f3ed87a6/href</a></iframe><p>As you can see we need to validate that the expected interface is correct. In order to do that we are going to need a function that I called isValidInterface, so let&#39;s TDD that function!</p><h3>Apply TDD not only for production code</h3><p>It is really funny that we keep testing and applying BDD and TDD to our flow, but yet, we did not write a single line for production code. Nevertheless, you can feel that we are setting a very solid base for our app, consisting on making assertions and predictions on how our app should behave and respond (that is why it is called behavioral driven testing).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByJ8YZf9zWvvwGdKtIPYew.jpeg" /><figcaption>yes, it’s really funny — Photo by <a href="https://www.pexels.com/@alex-green?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Alex Green</a></figcaption></figure><p>unit/validators.test.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25d3f046c32f4365d4e2a4333018515e/href">https://medium.com/media/25d3f046c32f4365d4e2a4333018515e/href</a></iframe><p>I feel comfortable with that assertion for now, the signature is an easy solution, something like this:</p><p>isValidInterface :: (Object, Object) -&gt; Boolean</p><p>Ok, let’s keep going:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad506aabe52fcc4b38d64a195e5c69f0/href">https://medium.com/media/ad506aabe52fcc4b38d64a195e5c69f0/href</a></iframe><p>It looks good, but the test is failing, isValidInterface is not defined.</p><p>Let’s define isValidInterface</p><pre>root<br>├── test<br>│   ├── integration<br>│   ├── mocks<br>│   └── unit<br>└── app<br>    └── validators.js</pre><p>validators.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ce5746981a86e0f847a6951a5044317/href">https://medium.com/media/5ce5746981a86e0f847a6951a5044317/href</a></iframe><p>and require it in the test like so:</p><p>validators.test.js</p><pre>const { isValidInterface } = require(&#39;../../app/validators&#39;)</pre><p>The error that the test throws will now look like this:</p><pre>operator: deepEqual<br>diff: &quot;true&quot; =&gt; &quot;undefined&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXJWXKtXwfKkzer7d4HOpw.jpeg" /><figcaption>it’s not working, I have doubts… — Photo by <a href="https://www.pexels.com/@keira-burton?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Keira Burton</a></figcaption></figure><p>Now, we have to implement the minimal code that will make the test pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6158b92c402f35cd05553ae5db145ac/href">https://medium.com/media/c6158b92c402f35cd05553ae5db145ac/href</a></iframe><p>This made the test pass, and we can refactor the code to make it more declarative:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bd7217d9184fa435a3228d39b9427a9/href">https://medium.com/media/8bd7217d9184fa435a3228d39b9427a9/href</a></iframe><p>Test is still passing, looks good, but what if we pass an array?</p><p>Let’s create another test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3206908cad9674b31fc5ab385ab33441/href">https://medium.com/media/3206908cad9674b31fc5ab385ab33441/href</a></iframe><p>Test fails, but that is okay. let’s add the minimal solution for this test to pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62d54aded788acf7771ba81ac64ff930/href">https://medium.com/media/62d54aded788acf7771ba81ac64ff930/href</a></iframe><p>Hooray! The test passed! but… it looks awful. I mean, it looks like I’m talking to a computer here, also using return statements inside if-else statements gives me the shivers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zebmb_pcAalncQc8veaaEA.jpeg" /><figcaption>he just saw a return inside an if-else — Photo by <a href="https://www.pexels.com/@benjaminlehman?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Benjamin Lehman</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/274e6dfba0a5abfd3d464b3f7e34f230/href">https://medium.com/media/274e6dfba0a5abfd3d464b3f7e34f230/href</a></iframe><p>I like this, but we can refactor our two tests into one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebbab7be2a449b032e7b4fac2a964e5b/href">https://medium.com/media/ebbab7be2a449b032e7b4fac2a964e5b/href</a></iframe><h3>Back to our cucumber step</h3><p>No we can add the dependency:</p><p>steps/generic.js</p><pre>const { isValidInterface } = require(&#39;../../../app/validators&#39;)</pre><p>Let’s move on to another step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ff9f7b378614105f065933a81f5b73b/href">https://medium.com/media/3ff9f7b378614105f065933a81f5b73b/href</a></iframe><p>That was easy right? Specifically, making simple assertions using a traverser to access nested props and defaulting to a safe empty array. Although, defaulting here can be confusing, but we are going to leave it there.</p><p>Now, I’m noticing a variation for this step:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bc56c522829187f9b6f7a4fd171a0b6/href">https://medium.com/media/4bc56c522829187f9b6f7a4fd171a0b6/href</a></iframe><p>What did we do in the TDD example? We assumed that it was just an object as input, and this is ok, but our step is assuming that body.data is an object and not an array. It is the perfect time to fix that, but we need to decide, adapt our isValidInterface to accept arrays, or modify our step.</p><p>Let’s do TDD (just in case) and write another test for our function.</p><h3>Always bet on TDD</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clNWo0zR0r-oghMCFMziwQ.jpeg" /><figcaption>he bet on WRDI (wild raw direct implementation) — Photo by <a href="https://www.pexels.com/@pavel-danilyuk?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pavel Danilyuk</a></figcaption></figure><p>Create a new test and be specific on what you write as description. It helps to understand what the functionality is that you are testing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe4b4a6de6bf6bf66195c7c254c7d0b8/href">https://medium.com/media/fe4b4a6de6bf6bf66195c7c254c7d0b8/href</a></iframe><ul><li>see it fail</li><li>implement minimal expression and see it pass</li><li>refactor</li></ul><p>Let’s modify our function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7bc26db1406d3a859834e4232c1cd96/href">https://medium.com/media/c7bc26db1406d3a859834e4232c1cd96/href</a></iframe><p>It passed, but… it looks repetitive right? Refactor then:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/289cd40e75fd8ea7df2c8c1a893a068f/href">https://medium.com/media/289cd40e75fd8ea7df2c8c1a893a068f/href</a></iframe><p>Wow, that looks really good. I like that following this process encourages developers to do the right thing:</p><ul><li>functional style</li><li>good abstractions</li><li>loosely coupled architecture</li><li>Inversion of control (no side effects)</li></ul><blockquote><em>Remember to add more test cases to try to break your functions, passing bad props, etc. It will force you to make decisions about error handling. Now, it is time to prove yourself!</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0SnYV38D2TGbdhP7k-aGA.jpeg" /><figcaption>This post is not boring him yet — Photo by <a href="https://www.pexels.com/@thatguycraig000?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Craig Adderley</a></figcaption></figure><h3>Back to cucumber steps. Again!</h3><p>There is just one thing left to implement, and at this point, it should be easy to implement. One variation, the restrictions case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5471fad8521de4b5bc3f91fa3985354/href">https://medium.com/media/e5471fad8521de4b5bc3f91fa3985354/href</a></iframe><p>The extra mapping methods, hashes, and rows are provided by <a href="https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/data_table_interface.md">cucumber</a></p><p>I think the signature of complyWith should be the same as the signature of isValidInterface.</p><p>complyWith :: (Object, Object) -&gt; Boolean</p><p>Let’s TDD again to implement this method.</p><h3>TDD is a discipline with high rewards</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WnmwmCVI_X5nU4o-wg3uA.jpeg" /><figcaption>witdrawing the rewards — Photo by <a href="https://www.pexels.com/@uriel-mont?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Uriel Mont</a></figcaption></figure><p>validators.test.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/722a86348e35b4263821090decb43499/href">https://medium.com/media/722a86348e35b4263821090decb43499/href</a></iframe><p>This is nice, but we have a problem. We are attacking the functionality from an incorrect perspective because we have smaller problems we should solve first. How are we going to do it to substitute less than with something that makes sense? My Idea is that we could map over the restrictions and substitute operator prop with a matching function. Let&#39;s see what I&#39;m talking about. Forget about the previous test, and start writing a new test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33416225eeacc0dd82c839c4747f0637/href">https://medium.com/media/33416225eeacc0dd82c839c4747f0637/href</a></iframe><blockquote><em>Remember to implement more cases or assertions. We checked only the first element, you should check at least two and make cases to handle errors.</em></blockquote><p>My implementation for this would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0f3bc3e7a97549b138940769bb45ff3/href">https://medium.com/media/a0f3bc3e7a97549b138940769bb45ff3/href</a></iframe><p>But refactoring is the key to success:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b611b6453efab16d70845de962388763/href">https://medium.com/media/b611b6453efab16d70845de962388763/href</a></iframe><p>Let’s go back to complyWith and start implementing with the previous helper which should be easier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e0ebca3d9499b21be51fa951925ea37/href">https://medium.com/media/0e0ebca3d9499b21be51fa951925ea37/href</a></iframe><p>And add a test case for input arrays:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8f9932f9cfb3d365660504f155ed6c6/href">https://medium.com/media/a8f9932f9cfb3d365660504f155ed6c6/href</a></iframe><p>At first it is tough, but see what we have accomplished:</p><ul><li>good coverage of your code</li><li>feeling of having done a good job</li><li>proof that you care about what you code</li></ul><blockquote><em>Remember to implement cases for handling errors, but be careful, don’t make new abstractions that you don’t need yet. Follow the process as it will tell you when to refactor, and that’s what you get with experience. First, write the test case. watch it fail, implement, watch it pass, refactor.</em></blockquote><p>Lastly, require complyWith from your generic steps file.</p><h3>Summary</h3><p>PM, customer and developer are on the same page when they talk and agree on scenarios for specific features.</p><p>We implemented the steps for that specific scenario in cucumber, using TDD in the process to design validators and other helper functions.</p><p>We did not write a single line of production code to set up our integration tests, which proves the BDD principle of black box testing or not caring about implementation details.</p><p>In <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-writing-code-4-5-afb96c1e5dda">part 4</a> we will dive into production code using TDD and finally satisfying our BDD tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd7fffac0c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD, BDD in Javascript World. Node. Framework setup. 2/5]]></title>
            <link>https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-framework-setup-2-5-ece3c0b46ef6?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece3c0b46ef6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cucumber]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Wed, 26 May 2021 13:41:07 GMT</pubDate>
            <atom:updated>2021-05-28T18:47:12.095Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-mental-models-1-5-83d32d32623b">part 1</a> of this series I wrote about some concerns to keep in mind and decisions we need to make before adding TDD, BDD to our workflow. In part 2 we are going to focus in setting up our environment.</p><p>You will learn:</p><ul><li>basic Cucumber JS setup for a Node project with BDD</li><li>basic Tape setup to unit test your functions</li></ul><h3>Set up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mip6PzgHL7f4XXJ86HFmgg.jpeg" /><figcaption>You can install cucumber as shown in the picture — Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a></figcaption></figure><p>$ npm i -D cucumber cucumber-pretty tape tap-nirvana</p><p>After installing dependencies, create this directory structure:</p><pre>test<br>├── integration<br>│   ├── features<br>│   │   └── sample.feature<br>│   ├── steps<br>│   │   └── generic.js<br>│   └── support<br>│       ├── hooks.js<br>│       └── world.js<br>└── unit<br>    └── sample.test.js</pre><p>sample.feature</p><pre>Feature: Simple maths<br>  In order to do maths<br>  As a developer<br>  I want to increment variables</pre><pre>  Scenario: easy maths<br>    Given a variable set to 1<br>    When I increment the variable by 1<br>    Then the variable should contain 2</pre><p>Gherkin language is a high level language that anybody can use, like your PM or the customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLAzG2QenC-q9NQxB1rxPw.jpeg" /><figcaption>Elegant people use Gherkin as well when they make a toast</figcaption></figure><p>The idea here is to talk to them to write some features that will serve us as acceptance criteria and testing scenarios at the same time.</p><h4>generic.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edb70153dfb95a75cb287fa73b5525bc/href">https://medium.com/media/edb70153dfb95a75cb287fa73b5525bc/href</a></iframe><p>Each gherkin step has to be implemented in cucumber via defineStep or any of its aliases (Given, When, And, Then). I recommend just to use defineStep because you could end up using any step starting with a Given, When, And, Then.</p><p>When Cucumber runs your scenarios it will check first for matches in the steps folder and execute them in order.</p><h4>hooks.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65ce93b4f71697b10331956b15cd3af8/href">https://medium.com/media/65ce93b4f71697b10331956b15cd3af8/href</a></iframe><p>We will leave hooks empty for now, but it will come in handy later on. Hooks will execute whatever we want before running all or specific scenarios.</p><h4>world.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d90580defd0291a1f90113ca14fc8aaa/href">https://medium.com/media/d90580defd0291a1f90113ca14fc8aaa/href</a></iframe><p>Cucumber has a global store at a scenario level that you can access via using this keyword in your steps. It is called world and you have to define it and set it as a constructor, even though it is empty.</p><h4>sample.test.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d534c0a85350322f641e113a3765142e/href">https://medium.com/media/d534c0a85350322f641e113a3765142e/href</a></iframe><p>For unit testing we will be using tape, as it is the simplest and most reliable tool if you don’t like magic. It generates TAP output. We don’t need nothing more to unit test in node. Another great thing is that you don’t need a runner to execute tests, just use the node command and provide a file path.</p><p>You should add the next npm scripts to package.json:</p><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;tape test/unit/*.test.js | tap-nirvana&quot;,<br>    &quot;watch&quot;: &quot;nodemon --exec \&quot;npm run test\&quot;&quot;,<br>    &quot;e2e&quot;: &quot;cucumber-js test/integration/features --require test/integration/steps --require test/integration/support -f node_modules/cucumber-pretty&quot;,<br>    &quot;watch:e2e&quot; : &quot;nodemon -e feature --exec \&quot;npm run e2e\&quot;&quot;<br>  },</pre><p>Let’s run our suites in watch mode, so they will run with every change in our project now, in one terminal:</p><p>$ npm run watch</p><p>and in another terminal:</p><p>$ npm run watch:e2e</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdlQ145-fhSc0JSA4Vy2PA.jpeg" /><figcaption>a family watching the tests pass, probably — Photo by <a href="https://www.pexels.com/@ketut-subiyanto?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Ketut Subiyanto</a></figcaption></figure><p>Then we have everything set up with tests running in watch mode to start doing some TDD.</p><h3>Summary</h3><p>We set up a cucumber js project with its typical structure, divided in:</p><ul><li>features written in Gherkin language</li><li>steps that implement features specs</li><li>support folder with hooks and world constructor</li></ul><p>We also set up a sample unit test and started running our test suites in watch mode.</p><p>In <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-writing-cucumber-features-3-5-bcd7fffac0c7">part 3</a> we focus on BDD testing with a use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece3c0b46ef6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD, BDD in Javascript World. Node. Mental models. 1/5]]></title>
            <link>https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-mental-models-1-5-83d32d32623b?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d32d32623b</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Wed, 26 May 2021 13:39:21 GMT</pubDate>
            <atom:updated>2021-05-28T18:47:38.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to this workshop series. It is a series consisting of five parts focusing on the application of BDD and TDD to our every day workflow for an express/NodeJS application.</p><p>In Part One we will discuss some mental models and patterns that will help us on our way to build a loosely coupled app.</p><p>You will learn:</p><ul><li>basic knowledge of how BDD and TDD integrates in your workflow</li><li>some mental models and preparation that need to be done before implementing BDD and TDD.</li><li>patterns and abstractions that go well with TDD</li><li>some functional programming concepts</li></ul><p>Come along and let’s start with some preparation.</p><h3>Some Preparation and Mental Models</h3><p>Test-driven development (TDD) encourages simple designs and inspires confidence.</p><p>It is a development process based on repetition of a simple cycle:</p><ul><li>Add a test and watch it fail</li><li>Write minimal expression of code to make the test pass</li><li>Refactor code</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRQFjFoCURHC5X0H2phweg.jpeg" /><figcaption>Like when your grandpa repeats the same joke every time — Photo by <a href="https://www.pexels.com/@100k-makhasette-2160826?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">100K Makhasette</a></figcaption></figure><p>We use this process because it encourages us to focus more on an interface rather than in the implementation.</p><h3>Declarative code</h3><p>We are not going to see tests yet, just some mental models.</p><p>Let’s take a look at one of my back-end’s modules</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a437ea8867e48a798793ffc50722966/href">https://medium.com/media/5a437ea8867e48a798793ffc50722966/href</a></iframe><p>let’s see how we can use that API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bd5354cda7d97ee96eedba38fb375ed/href">https://medium.com/media/4bd5354cda7d97ee96eedba38fb375ed/href</a></iframe><p>As you might have noticed, from the consumer perspective, the code reads pretty declarative, right?</p><ul><li>replaceParams takes a template and params to replace, and assigns the returned value to endpoint</li><li>composeURL takes a host and an endpoint and assigns the returned value to uri</li></ul><p>Declarative means that we see the WHAT not the HOW.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anpNZAjdUtF6Au6oTJTcCw.jpeg" /><figcaption>wa what — Photo by <a href="https://www.pexels.com/@100k-makhasette-2160826?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">100K Makhasette</a></figcaption></figure><p>We didn’t need to see the implementation, neither replaceParams nor composeURL.</p><blockquote><em>TDD encourages us to make a more readable and declarative code</em></blockquote><h3>Doing the research</h3><p>To first understand how we can apply TDD to our project we have to be honest with ourselves, do some research, and decide what is best for our purpose:</p><ul><li>patterns</li><li>abstractions</li></ul><h3>Patterns that work well</h3><p>Since I need to write a piece of code that acts as a middleware (backend that receives requests and composes new ones to other domains), I’m going to choose the simplest pattern ever, the module pattern, which looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6533205d99d08ee4b2d60e52651bce94/href">https://medium.com/media/6533205d99d08ee4b2d60e52651bce94/href</a></iframe><p>If you are asking why I don’t use function expressions like const method1 = () =&gt; {} it is because they don&#39;t hoist (look for javascript hoisting if you are not sure) this way you can open the file and see at a first glance the API you are exposing, method1 and method2, instead of having to scroll to the bottom of the file.</p><h3>Abstractions</h3><p>Fancy word, isn’t it? At the end of the day it means tools that you can use as a semantic binding for other tools. For example, something that helps us in composing larger programs with smaller ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60B4q9nS_XnAWg1PixpuyQ.jpeg" /><figcaption>I also compose the best music using pipe — Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a></figcaption></figure><p>I’m going to choose a composable abstraction that will help me implement the business logic (how data is changed/transformed) in a reusable and composable way.</p><p>Let’s talk about pipe. I’m always talking about pipe!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15f6af37fe65452d1a94cd6f6a2c3b8a/href">https://medium.com/media/15f6af37fe65452d1a94cd6f6a2c3b8a/href</a></iframe><p>The following is an equivalent:</p><pre>executeSecond(executeFirst(initialValue))</pre><pre> /*<br>  Order of execution due to eager evaluation<br> */</pre><p>There is just one rule that pipe has to follow: the signature of each function in each step has to be the same, and input and output should have the same type.</p><p>Or in a more concrete way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97bcce037aa00ecf7342401abf51c86c/href">https://medium.com/media/97bcce037aa00ecf7342401abf51c86c/href</a></iframe><h3>Doing the research (2)</h3><p>Patterns and abstractions will help us in writing a loosely coupled code, but we also need to decide which testing frameworks to use.</p><ul><li>unit test framework</li><li>integration test framework</li></ul><p>Just remember:</p><blockquote><em>With complicated frameworks you tend to do complicated things</em></blockquote><h3>Unit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuUJJPcO3SpmkMj2szJ6YQ.jpeg" /><figcaption>members of a special unit in my unit — Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a></figcaption></figure><p>I recommend you use <a href="https://www.npmjs.com/package/tape">tape</a>. It is the simplest and most transparent way to unit test your functions. It is also a nice fit to test in a node environment.</p><p>Get used to the way it works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dc1967f682224d1bfec5977d66f8a3a/href">https://medium.com/media/7dc1967f682224d1bfec5977d66f8a3a/href</a></iframe><p>Try to repeat the same actual, expected, equal structure. With these three, you can test everything.</p><blockquote><em>Forget about stubs, mocks or related stuff. Having to use those is just a code smell that says nothing good about your functions.</em></blockquote><h3>Integration</h3><p>Good old <a href="https://github.com/cucumber/cucumber-js">cucumber</a> will do the trick. We can write tests in a BDD Gherkin manner:</p><pre>Feature: Simple maths<br>  In order to do maths<br>  As a developer<br>  I want to increment variables</pre><pre>  Scenario: easy maths<br>    Given a variable set to 1<br>    When I increment the variable by 1<br>    Then the variable should contain 2</pre><p>BDD is a branch of TDD and it is more focused on testing how the integration between components and programs work. In part 2 we will be doing some hands on practice to gain experience.</p><h3>Summary</h3><p>To start doing TDD and BDD we need some preparation first. Deciding on what patterns and abstractions we are going to use to write more composable and loosely couple code is crucial. TDD will help us on our way to create simpler architectures reducing the amount of bugs we would have if we focused our attention only in the implementation.</p><p>Powerful ideas, let’s see how can we apply them in our workflow in <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-framework-setup-2-5-ece3c0b46ef6">part 2</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d32d32623b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD, BDD in Javascript world.]]></title>
            <link>https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-93e4f752c724?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/93e4f752c724</guid>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Wed, 26 May 2021 13:37:13 GMT</pubDate>
            <atom:updated>2021-06-11T14:47:11.541Z</atom:updated>
            <content:encoded><![CDATA[<p>The benefits of applying test-driven development (TDD) methodologies in our every day are huge:</p><ul><li>Tested code, great coverage</li><li>Modular and loosely coupled code</li><li>Great relation and understanding between customer — PM — developer</li><li><a href="https://www.researchgate.net/publication/3249271_Guest_Editors&#39;_Introduction_TDD--The_Art_of_Fearless_Programming">40% — 80% fewer bugs</a> in production</li><li>Can save development time with some experience</li></ul><p>TDD stands for Test Driven Development and the process consist on:</p><ul><li>Write a test and watch it fail</li><li>Implement minimal expression of code to make it pass</li><li>Refactor both test and code if needed</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saDRbrXH3L4ToCoTYAPZww.jpeg" /><figcaption>TDD is interesting and serious business at the same time — Photo by <a href="https://www.pexels.com/@masharaymers?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Masha Raymers</a></figcaption></figure><p>TDD saves everybody in your team a lot of time. Putting in place some continuous integration and deployment (CI/CD) will make sure that every change have to pass all other tests in the codebase before merging them.</p><blockquote><em>You will lose the “fear of change”</em></blockquote><p>If we complement TDD with Behavior driven development (BDD), then we can go home knowing we are doing the good thing.</p><blockquote><em>I like to sleep good at night, that is why I TDD and BDD</em></blockquote><p>TDD process is more focused in unit testing while BDD (branch of TDD) is more focused on producing integration tests with a concept we call “black box testing”.</p><h3>Pyramid of testing</h3><p>The problem I see that a lot of companies have is the “inverted pyramid of testing”. Firstly, it is not cost effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*JCfcbFmUzNIKIjdt.png" /></figure><p>Manual testing is very expensive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*JZb53jp4nvYGH0Fz.png" /></figure><p>Unit tests should form the base amount of tests in your project</p><p>I call it “the inverted pyramid” and it does not stand still for so long since manual testing is very inefficient and expensive. The more you go to the top the more expensive it is. The point here is not about replacing every manual test and say good bye to the QA team, no, I love my QA team mates! the point here is starting to take responsibility of what you create, what you code. Manual testing is still important, like exploratory testing and other forms, but we have to reduce the impact/cost of manual testing as much as we can. How? automating tests by adopting the BDD process.</p><p>Two obstacles that we are going to combat in the series:</p><ul><li>laziness</li><li>inexperience</li></ul><p>You will become a better developer, your team mates will love your contributions and your customers will be in the same page as you are on what features have to be delivered.</p><p>The series consists on applying BDD, TDD workflow in</p><ul><li>a Node JS environment where we will create an express app with a declarative and functional style.</li><li>A front-end environment where we will create a React app with the help of browser automation.</li></ul><h3>Why</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipIZU_6xEWsyxCZL1qZ8Og.jpeg" /><figcaption>A member of the TDD enlightenment movement — Photo by <a href="https://www.pexels.com/@masharaymers?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Masha Raymers</a></figcaption></figure><p>As I always say to my team mates,</p><blockquote><em>let’s do what we have to do to sleep better at night</em></blockquote><p>The above is just a consequence of feeling responsible for what we code. To have a safety net of tests always enhances confidence reducing the “merge fear” or “fear of change” when it comes to adding new features or refactoring.</p><h3>But we don’t have time to do TDD</h3><p>It is just a misconception that TDD slows down the delivery model. Normally an unexperienced developer would spend more time on the process because firstly, one needs to learn how to do things and adapt. Also it requires discipline.</p><blockquote><em>A mentor can break the mental barrier that most of newcomers have.</em></blockquote><p>It is really normal to try adopting TDD and quit 5 minutes later, it feels boring and developers get discouraged if they don’t know what to test, where to put the focus on or how to do it. As I commented in the “backend series” you need to first understand patterns and some models that work better with TDD. now would be a good time to revisit them. The process will help you understand them and also will improve your application architecture.</p><p>Experienced developers will experiment an increase in speed when implementing new features and don’t get me started with the amount of future bugs that using the technique avoids!</p><blockquote><em>TDD is actually the fastest and more secure way to get features out there</em></blockquote><h3>What about Legacy code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv_G3H7qGSQqd90oMk44OQ.jpeg" /><figcaption>Finding the end of the rabbit hole and finally free— Photo by <a href="https://www.pexels.com/@masharaymers?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Masha Raymers</a></figcaption></figure><p>You have a customer, they hired another company months ago to build them software, they didn’t do TDD and they have a big problem. Hold on to your seat!</p><p>Nobody wants to admit that they have legacy code. The cadence was feature-based and now it is full of spaghetti code with innumerable “if else” (branching) statements everywhere. Now it is really difficult to do or refactor something without breaking other logic.</p><blockquote><em>But they promised us they will refactor the code</em></blockquote><p>We have to be very careful at this point because usually the same developer that did not test its code is not going to test it “before starting the refactor process“.</p><h3>How to apply TDD to legacy code?</h3><p>You cannot, TDD is a process to build code, but if you want to start a process of refactoring so you can apply TDD afterwards, we can start with something.</p><p>We can start creating integration tests focusing on the functionality of the application/system. This approach would be called “black box testing”, it means that we don’t need to care about implementation details.</p><p>Nice right?</p><p>It makes sense since what we have is something we don’t understand at a lower level. Using Gherkin and cucumber you can create a nice “feature” suite or even getting some coverage with POSTMAN if we are talking about back-end. That should be enough.</p><p>When we finish writing those integration tests, we can approach a refactor, isolating different parts.</p><p>If you can rewrite the feature it would be a nice time to set up an “assert” library of your choice. In javascript ecosystem we have lots of options. If we do that we can start a rewrite with TDD, writing the test first, watch it fail, implement the minimal expression of the assertion, seeing it pass, and refactor if needed both code and test. It is a discipline.</p><p>But sometimes we don’t know where to start. This is my suggestion:</p><ul><li>Choose the simplest library like “tape”</li><li>Start testing</li></ul><h3>Start testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtaYEpzdEi4SC97qqBCx2g.jpeg" /><figcaption>I loved my mocks as well, but you have to let them go — Photo by <a href="https://www.pexels.com/@masharaymers?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Masha Raymers</a></figcaption></figure><p>Don’t bother about TDD now. It is really important that you get used to test your craft. You will find obstacles, that’s for sure:</p><ul><li>How can mock this and that?</li><li>How can I set and remove the state before and after the tests</li></ul><p>I have been there. They are all code smells.</p><blockquote><em>Separate your side effects from your pure functions</em></blockquote><p>TDD and unit testing work better with pure functions</p><blockquote><em>A pure function will produce always the same output when receiving the same input</em></blockquote><p>Understanding this separation of concerns will lead you to better architectures.</p><p>I use BDD in my process, integration tests that cover those parts and side effects that I should not test with unit tests.</p><h3>Know your tools</h3><p>Know your tools, your unit test framework, or even try find different patterns that are going to help you implement features with TDD, does not matter if your doing the test after implementing the code (for now), but start testing now. You need to “fail fast” to understand the “why” of some concepts.</p><p>Usually when you build a codebase with TDD, if you do it right, you find out that the separation of concerns happens naturally:</p><ul><li>the business logic or how data is processed is in one place</li><li>network layer (http clients)</li><li>database connections</li><li>logging tools</li><li>other side effects</li></ul><p>I actually would not mind having this tree in my app</p><pre>app<br>├── pure-code<br>└── side-effects</pre><p>Clear right?</p><h3>Program to interfaces, not implementations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WglKHDFU_m2k_aZnaSmwig.jpeg" /><figcaption>I was beating about the bush before TDD. She’s beating the bush — Photo by <a href="https://www.pexels.com/@masharaymers?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Masha Raymers</a></figcaption></figure><p>That means that TDD enforces you to focus first on how would you like to use the functionality.</p><p>In my mind I think first about declarative ways to use methods</p><pre>composeName(&#39;Alan&#39;, &#39;Smith&#39;)</pre><p>knowing the signature of the function helps in composing the assertion.</p><pre>composeName :: (String, String) -&gt; String</pre><p>At some point you will have to import the module to test the method. What that module exposes is its API, and an API is nothing more than an interface. As you will see your architecture will get simpler and extendable.</p><blockquote><em>Focus on the user, focus on the interface</em></blockquote><p>If you are interested, check out my series on <a href="https://sergueymartinez.medium.com/tdd-bdd-in-javascript-world-node-mental-models-1-5-83d32d32623b">TDD, BDD in nodeJS</a></p><p>Ciao!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93e4f752c724" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Functional Swift for Beginners]]></title>
            <link>https://medium.com/tribalscale/intro-to-functional-swift-for-beginners-1f86764a8822?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f86764a8822</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Tue, 18 May 2021 18:23:16 GMT</pubDate>
            <atom:updated>2022-10-05T14:59:57.271Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By: Serguey Martinez, Staff Engineer, TribalScale</em></p><p>At first, I didn’t see my teammates using some functional tools and patterns that swift provides. I didn’t know either that those patterns existed!</p><p>Don’t get me wrong, my team mates write quality code…</p><blockquote>I saw nice structured code and just the right amount of “if lets”, “guard lets” and “?”</blockquote><p>So I thought I should ask some questions to the language and see if I could apply patterns that I’ve used before in my beloved <strong>Javascript,</strong> or my old buddy <strong>Haskell</strong>.</p><h3>Higher order functions</h3><p>Functions in Swift are special citizens; meaning that you can pass functions to other functions, they can return functions, or they can hold other functions in their pouch, like kangaroos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2O5UEpN21gM4tZVEtRFmQw.jpeg" /><figcaption>A function holding a kangaroo— Photo by <a href="https://www.pexels.com/@ethan-brooke-1123775">Ethan Brooke</a></figcaption></figure><p>Let me walk you through a perfect example to demonstrate why this is so incredible and why I love functions.</p><h3>Partial application</h3><p>Let’s start with a simple case, and say I need a function called <strong>addOne.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/939da1d2ab4ca72f5efeddb23ee14230/href">https://medium.com/media/939da1d2ab4ca72f5efeddb23ee14230/href</a></iframe><p>Simple, but not very interesting. The problem is that some enthusiastic mind asked for an <strong>addTwo</strong> feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5NxLaGeqn0dPWvltzAKxQ.jpeg" /><figcaption>I.can’t?believe?it?— Photo by <a href="https://www.pexels.com/@liza-summer?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Liza Summer</a></figcaption></figure><p>Okay, no problemo, gist please:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21ddfd0c166ad9d2eae3a7e4468197f1/href">https://medium.com/media/21ddfd0c166ad9d2eae3a7e4468197f1/href</a></iframe><p>That was easy!</p><p>But my grandpa has trouble doing simple calculations and he is asking for an <strong>addThree</strong> function; it will be very useful for when he goes to play cards with his friends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_De1SDHGxRnaP379hDSISg.jpeg" /><figcaption>An actor playing my grandpa — photo by <a href="https://www.pexels.com/@mart-production?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Mart Production</a></figcaption></figure><p>I also have friends in the financial sector that would pay high sums for an <strong>add284</strong> function!</p><p>You see where I’m going?</p><p>So, how can I create any function that I want, such as <strong>add284</strong>, but with the same function that creates <strong>addThree</strong>?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8503b02de8cf14b5c91b93b46a98d2b0/href">https://medium.com/media/8503b02de8cf14b5c91b93b46a98d2b0/href</a></iframe><p><strong>partialAdd</strong> is a function applied in two steps, or a function that returns another function.</p><p>It’s a clever way to refactor our code, but how can <strong>addTwo</strong>, <strong>addThree</strong> or <strong>addALot</strong> remember that it is a 2, a 3 or a 284 of numbers it has to add?</p><p>Well, because of closures.</p><h3>Closures</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgbomYkI7u4wD_896FxYbA.jpeg" /><figcaption>Closures make you think while you’re at the phone — Photo by <a href="https://www.pexels.com/@olly?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Andrea Piacquadio</a></figcaption></figure><p>Closures sounds like a fancy term, but it’s the glue that sticks <strong>partialAdd</strong> with all the other functions that it generates. Every function that is generated from <strong>partialAdd,</strong> will have direct access to objects and values that were passed or created to/in <strong>partialAdd.</strong></p><p>And it doesn’t matter if I use <strong>addThree</strong>, 2, 5 or 100 times, it will always have access to the 3 we passed to its creator at the start.</p><p>Imagine a rope or a lasso being thrown at <strong>partialAdd</strong> to get the input values as if those nostalgic functions were longing for them since they were conceived. Poetic.</p><h3>Composition</h3><p>Yesterday I received a call from my friend at the zoo. He has problems with counting the zebras, and he needs to check everyday just in case any zebra is missing or mistaken for a crosswalk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6nZStHlxIxcRbPCIH6tGg.jpeg" /><figcaption>Zebras, not crosswalks — photo by <a href="https://www.pexels.com/@hendrikcornelissen?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Hendrik Cornelissen</a></figcaption></figure><p>He wants to use the functions <strong>addOne</strong>, <strong>addTwo</strong> and maybe more in conjunction. So, I told him that he could do some composition with the functions he already has.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7925aa9a959f6db23fdc5bc18dc41385/href">https://medium.com/media/7925aa9a959f6db23fdc5bc18dc41385/href</a></iframe><p>But there is another way that he might like, as it’s easier to read and you can expect that functions will be executed from left to right, the opposite of the example above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dd66a24f49c1d8a9cb60c245b0ec7bb/href">https://medium.com/media/0dd66a24f49c1d8a9cb60c245b0ec7bb/href</a></iframe><p>Pipe is just another function using partial application and closures, with small differences:</p><ul><li>the inner function (the function that is returned first) inside pipe will have access to an array of <strong>fns </strong>that was fixed<strong> </strong>instead of a simple <strong>Int. </strong>Remember closures.</li><li>we are passing functions in the first step. <strong>Higher order functions</strong> can accept other functions as parameters.</li><li>pipe is still a partial application but it is immediately invoked in the same line with the syntax “(fn1, fn2)(Int)”</li></ul><p>We iterate through every function in the pipe, one at a time. With <strong>reduce</strong>, we can apply functions, passing values that were calculated in the previous loop and return a new value that the next loop will use.</p><p>My friend was impressed: we had found an elegant way of composing functions.</p><h3>Pipe as a generic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCm31KOcWPDrj5l74b8cjw.jpeg" /><figcaption>It’s hard to be elegant and humble— Photo by <a href="https://gist.github.com/sergueyarellano/406f989b6547c47eb4baeae3dc897800">Leah Kelley</a></figcaption></figure><p>Pipe can be widely used if we convert it as a generic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7df9b9546fd30cdaebfd3fbe9bc6dad/href">https://medium.com/media/b7df9b9546fd30cdaebfd3fbe9bc6dad/href</a></iframe><p>Imagine the possibilities!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lW0sugl60rkzYw9kNb4Jwg.jpeg" /><figcaption>Lots of possibilities and ice cream — photo by <a href="https://www.pexels.com/@amina-filkins?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Amina Filkins</a></figcaption></figure><p>We could even write a library that composes <strong>HTML</strong>, <strong>request strings</strong> or something more <strong>procedural</strong> that could go deeper into category theory (out of the topic today), for example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cc622943dbe91ef1c7533a65241763c/href">https://medium.com/media/8cc622943dbe91ef1c7533a65241763c/href</a></iframe><p>I’ll leave it there for now - I hope it was fun and informative!</p><p>Ciao!</p><p>For more information on functions in Swift, <a href="https://www.tribalscale.com/schedule-a-chat">click here to speak to one of our experts.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*MzkYWUusEz1-2FYggEcHdg.png" /></figure><p>Serguey Martinez is a Staff Engineer at TribalScale. He is passionate about functional programming.</p><p><a href="http://www.tribalscale.com/"><em>TribalScale</em></a><em> is a global innovation firm that helps enterprises adapt and thrive in the digital era. We transform teams and processes, build best-in-class digital products, and create disruptive startups. Learn more about us on our </em><a href="http://www.tribalscale.com/"><em>website</em></a><em>. Connect with us on </em><a href="http://twitter.com/tribalscale"><em>Twitter</em></a><em>, </em><a href="https://www.linkedin.com/company/tribalscale"><em>LinkedIn</em></a><em> &amp; </em><a href="http://facebook.com/tribalscale"><em>Facebook</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f86764a8822" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tribalscale/intro-to-functional-swift-for-beginners-1f86764a8822">Intro to Functional Swift for Beginners</a> was originally published in <a href="https://medium.com/tribalscale">TribalScale</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Push Notifications How-To: Firebase, AWS cron jobs & EventBridge]]></title>
            <link>https://medium.com/tribalscale/push-notifications-how-to-firebase-aws-cron-jobs-eventbridge-58eb937f9eae?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/58eb937f9eae</guid>
            <category><![CDATA[eventbridge]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[javascrip]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 16:52:00 GMT</pubDate>
            <atom:updated>2022-10-05T15:12:25.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HULDD72gtF-_9FQasd8ASQ.jpeg" /></figure><p>Let’s say we want to notify our users if they are subscribed to some sort of daily reminder. Here we can use an AWS cron job along with EventBridge to send push notifications with firebase.</p><p>Let’s start with a simple diagram to identify the different parts or steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45Pl3CJ-4gcuNhlJTBnYLw.png" /></figure><h3>Step 1</h3><p>We retrieve the reminders from our database:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/146f36a3db514c69afbcc0332472315b/href">https://medium.com/media/146f36a3db514c69afbcc0332472315b/href</a></iframe><p>User <strong>111</strong> has three activities in our reminders table:</p><ul><li><strong>activity1</strong> is enabled but the user completed the activity for the day. So we shouldn’t notify the user about this activity;</li><li><strong>activity2</strong> is not enabled, and therefore should not be notified about the activity either;</li><li><strong>activity3</strong> is enabled and hasn’t been completed for the day. We have to notify the user about this activity.</li></ul><p>Now we’re going to send these items to our EventBridge bus so the next entity can take care of them. However, we still have some problems…</p><h3>Problems</h3><p>Eventbridge has a limitation of ten entries every time we send the events to the bus.</p><p>Because we are going to produce an <strong>event per reminder</strong> found for that day, the second step should receive a maximum of ten reminders at a time. We will talk about that later…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/759f1339e40605264001f9d2144eb57b/href">https://medium.com/media/759f1339e40605264001f9d2144eb57b/href</a></iframe><p>If there are a lot of items to handle, Dynamodb could return a paginated response. We would miss some items if we don’t give a solution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b483d6c01bbb343112abd4c99c5d2a5/href">https://medium.com/media/8b483d6c01bbb343112abd4c99c5d2a5/href</a></iframe><h3>Solutions</h3><p>Let’s tackle the pagination issue first.</p><p>The idea is to retry our queries every time we get a paginated response. Also it’s important that we return the responses each time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWgNLdP7haXnnFyoSUN02Q.png" /></figure><p>generators to the rescue!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e31ec846dcd8df6848a174a87f554e83/href">https://medium.com/media/e31ec846dcd8df6848a174a87f554e83/href</a></iframe><p>The query to the DB looks as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85b034bf0aac86599977378fbf59d6bb/href">https://medium.com/media/85b034bf0aac86599977378fbf59d6bb/href</a></iframe><p>Notice the <strong>limit</strong> for every query.</p><p>At this point, we can iterate through the responses that the generator returns. The generator is returning promises so an async iterator is needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b36e4b1c5874e1a378c8d1674136c1c2/href">https://medium.com/media/b36e4b1c5874e1a378c8d1674136c1c2/href</a></iframe><p>Notice how handy having retryQuery() is. A generator is useful when you don&#39;t know how many iterations you are going to need. Magic!</p><h3>Step 2</h3><p>As a subscriber the step 2 handler has to listen to the cron.query source (step 1) and do two things:</p><ul><li>filter invalid activities inside each reminder;</li><li>split each reminder into a new event.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4f4oGmvtN0tABqNq3hFhg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aac8be435707b74409d30a2d422697da/href">https://medium.com/media/aac8be435707b74409d30a2d422697da/href</a></iframe><h3>Step 3</h3><p>Easy! Follow the steps in <a href="https://medium.com/@jullainc/firebase-push-notifications-to-mobile-devices-using-nodejs-7d514e10dd4">this article</a>.</p><ul><li>Set up Firebase SDK (initialize app)</li><li>compose message</li><li>send the message</li></ul><p>There is a catch, and that is the need for an FCM token. An FCM token identifies the user’s device. It’s important to have it in our <strong>reminders</strong> database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3022d5512b106fd1abe1a5bea69fb93c/href">https://medium.com/media/3022d5512b106fd1abe1a5bea69fb93c/href</a></iframe><h3>Summary</h3><p>We could have used step-functions instead, but EventBridge works as expected and it’s pretty simple. Due to lambda’s auto-scaling, we don’t need to care about concurrency. Just don’t exceed event bridge limitations (10 events at once). You can choose the communication layer of your choice (even a different pub-sub pattern with SNS).</p><p>And there we have it! Integrating push notifications with Firebase is as easy as that! We tackled our problem in three simple steps:</p><ol><li>Get the reminders from our database table;</li><li>Filter invalid reminders;</li><li>Send reminders to firebase for push notifications.</li></ol><p>Special thanks to <a href="https://medium.com/u/9d89f76eed1b">Ryan Bui</a> for co-authoring this article</p><p>Happy hacking!</p><p>Have questions about integrating push notifications with Firebase? <a href="https://www.tribalscale.com/schedule-a-chat">Click here to speak to one of our experts.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/0*jLZPR_yK3F_fPk5h.jpeg" /></figure><p>Serguey is a Javascript developer with experience in cloud architectures and a TDD advocate.</p><p><a href="http://www.tribalscale.com/"><em>TribalScale</em></a><em> is a global innovation firm that helps enterprises adapt and thrive in the digital era. We transform teams and processes, build best-in-class digital products, and create disruptive startups. Learn more about us on our </em><a href="http://www.tribalscale.com/"><em>website</em></a><em>. Connect with us on </em><a href="http://twitter.com/tribalscale"><em>Twitter</em></a><em>, </em><a href="https://www.linkedin.com/company/tribalscale"><em>LinkedIn</em></a><em> &amp; </em><a href="http://facebook.com/tribalscale"><em>Facebook</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58eb937f9eae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tribalscale/push-notifications-how-to-firebase-aws-cron-jobs-eventbridge-58eb937f9eae">Push Notifications How-To: Firebase, AWS cron jobs &amp; EventBridge</a> was originally published in <a href="https://medium.com/tribalscale">TribalScale</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Proxy an S3 Static Website]]></title>
            <link>https://medium.com/tribalscale/how-to-proxy-an-s3-static-website-49a6dd0dba56?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/49a6dd0dba56</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Mon, 07 Dec 2020 19:06:44 GMT</pubDate>
            <atom:updated>2023-02-01T16:40:19.431Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Read Part 1: How To Configure AWS Route 53 </strong><a href="https://medium.com/tribalscale/how-to-configure-aws-route-53-c8fa99ce66fb"><strong>here</strong></a><strong>.</strong></p><p>I’ve been having a problem with microservices in AWS for a while. How do integrate a swagger UI endpoint within the API itself?</p><p>Ideally, I’d have this:</p><pre>api.mydomain.com/docs<br>api.mydomain.com/path1<br>api.mydomain.com/path2<br>...</pre><p>There is actually a way I came up with to achieve this that doesn’t need CloudFront:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*951DaVip-iypi4OfXWkUQA.png" /></figure><p>So why without CloudFront? I don’t want to invalidate the CloudFront instances every time I deploy a new version of my spec and wait until the CDN “unregisters” or “un-caches” the previous content. I want it to be instantaneous.</p><h3>Creating an S3 static website</h3><p>Remember to give the bucket the appropriate permissions. You can follow the <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html">AWS guide</a> and upload content.</p><p>If you want to use the serverless framework I recommend the S3 Sync plugin. It will create the bucket, add the permissions, and stay in sync each time you deploy your service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1818127f680e6a7a4a7dbbf8c2d94a33/href">https://medium.com/media/1818127f680e6a7a4a7dbbf8c2d94a33/href</a></iframe><h3>Create an API REST</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qa5AdCUZUjPjtXdZ.png" /></figure><p>or do so with serverless using CloudFormation syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/405e6e360ecf6e52a541cbe1c04603a9/href">https://medium.com/media/405e6e360ecf6e52a541cbe1c04603a9/href</a></iframe><h3>Create an API structure</h3><p>The third step consists of creating the structure, resources, and methods for the newly created API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qN_V3OTb-mQlueAk.png" /></figure><p>The root method has to proxy the requests to the URL of your website:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*InlVyWEVMHIDzFdB.png" /></figure><p>Click on the integration request part to set the endpoint URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*__h2fpMTUQvsm04K.png" /></figure><p>If you don’t want to do it manually you can do it in serverless in the resource part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/581f2c9ff0a24091a73bbe415f86c684/href">https://medium.com/media/581f2c9ff0a24091a73bbe415f86c684/href</a></iframe><p>Our problem now is that if you access the API gateway endpoint via &lt;gatewayID&gt;.execute-api.&lt;region&gt;.amazonaws.com/&lt;stage&gt; you will see that your index.html gets downloaded because it was proxied but other resources that the HTML wants to download do not get resolved. It has a problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RW4jMZjdDArDAuwekI9jlw.jpeg" /></figure><h3>The Problem</h3><p>If the bucket has the following structure:</p><pre>index.html<br>swagge-ui.css</pre><p>index.html:</p><pre>&lt;link <em>rel</em>=&quot;stylesheet&quot; <em>type</em>=&quot;text/css&quot; <em>href</em>=&quot;swagger-ui.css&quot; &gt;</pre><p>using this URL in a browser will retrieve the index.html:</p><pre>xxxxxxkdu.execute-api.us-east-1.amazonaws.com/dev</pre><p>and will attempt to retrieve the CSS resource without resolving with the correct stage and cause an error:</p><pre>xxxxxxkdu.execute-api.us-east-1.amazonaws.com/swagger-ui.css</pre><h3>The Solution</h3><p>The solution is to adapt the <strong>href</strong> of your resource to this:</p><p>index.html:</p><pre>&lt;link <em>rel</em>=&quot;stylesheet&quot; <em>type</em>=&quot;text/css&quot; <em>href</em>=&quot;dev/swagger-ui.css&quot; &gt;</pre><p>Yes, it still won’t work because you didn’t tell your gateway how to resolve that. Also, I’m not happy with using arbitrary dev in the <strong>href</strong>. What happens when we deploy to prod? In my case I’m using Route 53 to have nice subdomain records like:</p><pre>dev.mydomain.com/docs<br>staging.mydomain.com/docs<br>prod.mydomain.com/docs</pre><p>So my index.html will look like this:</p><pre>&lt;link <em>rel</em>=&quot;stylesheet&quot; <em>type</em>=&quot;text/css&quot; <em>href</em>=&quot;docs/swagger-ui.css&quot; &gt;</pre><p>Firstly, you will need to buy/transfer a domain, get a public certificate (TLS HTTPS), and create some mappings within custom domains in API gateway but that is another topic.</p><p>Remember our API structure?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p6QoYl9RxMKX3qil.png" /></figure><p>We created a resource called /{item} that will resolve to S3 bucket content and get back with the resource to the browser. There are two things to configure here:</p><ul><li>permissions for the API gateway to access the bucket contents</li><li>MIME types to return to the browser with the appropriate headers so it understands what the resource is. Otherwise, you will get resources but the browser won’t know how to treat them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3d_fxDJwcLyMhZfw.png" /></figure><p>In method request you need to configure paths and headers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ncu1sm6jtBJCIrmJ.png" /></figure><p>In integration request you need to configure the headers and path with the following values.</p><p>It is important to use path override here, the idea is to map the http path to the bucket resource. My bucket&#39;s name is swagger-site-dev</p><p>I will return to role permissions later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6JL5dHAwi0yWtZRD.png" /></figure><p>For method response we have to make Content-Type and Content-Disposition available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OM-vuOmPR297v_8f.png" /></figure><p>And map those headers to the response values from S3 in integration response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1R-3MRvNKENEgpRW.png" /></figure><p>A way to automate this in serverless with CloudFormation syntax:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9cdbdcf7e29cd399e6c9585aaf244ec/href">https://medium.com/media/a9cdbdcf7e29cd399e6c9585aaf244ec/href</a></iframe><h3>Creating a role to give permissions to S3</h3><p>A way to automate this in serverless would be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44940b76d73c8bebd4d0aeeaaccc350d/href">https://medium.com/media/44940b76d73c8bebd4d0aeeaaccc350d/href</a></iframe><p>If you are using the console go to IAM -&gt; roles and create a role with permissions</p><ul><li>AmazonS3ReadOnlyAccess as an AWS managed policy</li></ul><p>and trust relationships</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/234dd91a3c405f4cbf27c4536e404b79/href">https://medium.com/media/234dd91a3c405f4cbf27c4536e404b79/href</a></iframe><p>After having this role you can add it to integration request -&gt; execution role .</p><h3>Summary</h3><p>We created an S3 website and we are accessing it via API gateway, giving us the chance to redirect calls from Route 53 and subdomain records without the need to use CloudFront.</p><p>Not using CloudFront means that every time we update the S3 website content we don’t have to invalidate the CDN content first; it gets updated instantly. We are also reducing costs and extra complications of maintaining several CloudFront instances.</p><p>To do that we gave our API a specific structure that will:</p><ul><li>proxy to S3 website when accessing the root path /</li><li>retrieve specific objects from the bucket when accessing child path /{item}</li></ul><p>It looks a little hack-y, but the process is nevertheless logical!</p><h4>Have any questions about our development capabilities? <a href="https://www.tribalscale.com/schedule-a-chat">Click here to chat with one of our experts.</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*F3F-Sd17mCL-xtyvyyT3sA.jpeg" /></figure><p>Serguey is a Javascript developer with experience in cloud architectures and a TDD advocate.</p><p><a href="http://www.tribalscale.com/"><em>TribalScale</em></a><em> is a global innovation firm that helps enterprises adapt and thrive in the digital era. We transform teams and processes, build best-in-class digital products, and create disruptive startups. Learn more about us on our </em><a href="http://www.tribalscale.com/"><em>website</em></a><em>. Connect with us on </em><a href="http://twitter.com/tribalscale"><em>Twitter</em></a><em>, </em><a href="https://www.linkedin.com/company/tribalscale"><em>LinkedIn</em></a><em> &amp; </em><a href="http://facebook.com/tribalscale"><em>Facebook</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49a6dd0dba56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tribalscale/how-to-proxy-an-s3-static-website-49a6dd0dba56">How to Proxy an S3 Static Website</a> was originally published in <a href="https://medium.com/tribalscale">TribalScale</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Configure AWS Route 53]]></title>
            <link>https://medium.com/tribalscale/how-to-configure-aws-route-53-c8fa99ce66fb?source=rss-4171bb0fc143------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8fa99ce66fb</guid>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[aws-route53]]></category>
            <dc:creator><![CDATA[Serguey Arellano Martínez]]></dc:creator>
            <pubDate>Fri, 27 Nov 2020 20:34:27 GMT</pubDate>
            <atom:updated>2023-02-01T16:41:00.883Z</atom:updated>
            <content:encoded><![CDATA[<p><em>by Serguey Martinez, Staff Engineer</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L33aJipUdlSaDSLyd7wWCg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@weareprocreator">Procreator UX Design Studio</a></figcaption></figure><p>If your architecture is based on microservices it’s a really good idea to buy a domain in Route 53 and make the connections with API gateway so that you can enjoy URL’s like:</p><pre>dev.mydomain.com/docs dev.mydomain.com/microservice-basePath dev.mydomain.com/another-microservice-basePath </pre><pre>prod.mydomain.com/docs prod.mydomain.com/microservice-basePath prod.mydomain.com/another-microservice-basePath</pre><p>In this quick tutorial, I’m going to show you how to configure AWS Route 53. The first step is to buy a domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnXtyqr480wl0hQYloiQyA.png" /></figure><p>Next, go to AWS certificate manager and request certificates for the subdomains that you will need. Heads up that AWS requires you to have TLS encryption.</p><p>So, choose the email owner to verify the certs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6534l02ZJE48f2CzduDejw.png" /></figure><p>Then, wait for them to get issued…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f30K058uFJSjJLqYu7uNUg.png" /></figure><p>Once you have the certificates issued let’s go to API gateway -&gt; custom domains -&gt; create.</p><p>The domain name here should be something like dev.mydomain.com or api.example.com depending on the certificates you requested.</p><p>Choose the appropriate certificate and create the custom domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLvpozrN9uYxIGcDsYQrcA.png" /></figure><p>You can map now which API rest will handle which basePath.</p><p>In the example below if we try to access the URL https://dev.mydomain.com/docs it will delegate the request to swagger-dev API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhP-QIs2e-IoVJnwMUM1uw.png" /></figure><p>In this case, swagger-dev has the following structure. Remember that if you are mapping X basepath in this case docs, then you don&#39;t need to create another X basepath in the API where the requests are being delegated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/0*-KcpEKcyaNH4RCKX.png" /></figure><p>The last step consists of creating a record in Route 53 hosted zones. Whenever you buy a domain a hosted zone is created for you automatically. You can see your name servers (NS) and start of authority (SOA). On very rare occasions you have to touch those configurations — be careful not to do it now.</p><p>Go to Route53 -&gt; hosted zones -&gt; your domain -&gt; create record -&gt; simple routing. As the record name you should put the name of the subdomain: api, dev, etc.</p><p>In route traffic to, choose the API gateway alias you created in custom domains for a specific service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*iRy22u7m9gcIE6VS.png" /></figure><h3>Summary</h3><p>We just created the recommended flow that will support a microservices development with Route 53 and API gateway. Due to the limit of cloud formation resources set to 200 we can split our services into microservices with dedicated business logic.</p><h4>Have any questions about our development capabilities? <a href="https://www.tribalscale.com/schedule-a-chat">Click here to chat with one of our experts.</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*vjDECqAbouMq21a4xKuJbw.png" /></figure><p>Serguey is a Javascript developer with experience in cloud architectures and a TDD advocate.</p><p><a href="http://www.tribalscale.com/"><em>TribalScale</em></a><em> is a global innovation firm that helps enterprises adapt and thrive in the digital era. We transform teams and processes, build best-in-class digital products, and create disruptive startups. Learn more about us on our </em><a href="http://www.tribalscale.com/"><em>website</em></a><em>. Connect with us on </em><a href="http://twitter.com/tribalscale"><em>Twitter</em></a><em>, </em><a href="https://www.linkedin.com/company/tribalscale"><em>LinkedIn</em></a><em> &amp; </em><a href="http://facebook.com/tribalscale"><em>Facebook</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8fa99ce66fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tribalscale/how-to-configure-aws-route-53-c8fa99ce66fb">How to Configure AWS Route 53</a> was originally published in <a href="https://medium.com/tribalscale">TribalScale</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>