<?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 Santiago Vilar on Medium]]></title>
        <description><![CDATA[Stories by Santiago Vilar on Medium]]></description>
        <link>https://medium.com/@smvilar?source=rss-14f56fc78735------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*J5edkjv3SRrgIRZs.</url>
            <title>Stories by Santiago Vilar on Medium</title>
            <link>https://medium.com/@smvilar?source=rss-14f56fc78735------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 01:15:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smvilar/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[Stop duplicating constants between JS and CSS]]></title>
            <link>https://levelup.gitconnected.com/stop-duplicating-constants-between-js-and-css-40efd253a945?source=rss-14f56fc78735------2</link>
            <guid isPermaLink="false">https://medium.com/p/40efd253a945</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Santiago Vilar]]></dc:creator>
            <pubDate>Fri, 31 Jul 2020 00:53:21 GMT</pubDate>
            <atom:updated>2020-08-04T02:13:41.633Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two techniques to prevent the repetition of constants in JS and then in CSS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*APwkjd3D9FdMZy22" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We know that having more than one source of truth can only result in madness. But something I encountered in several front-end codebases is the repetition of style constants (colors, fonts, sizes) in CSS and in JS. We put the primary color in the CSS in a nice variable, but then we need it in our JS code (for whatever valid reason it is), so we go ahead and create a constant for it, because we’re not going to hardcode that value, oh no! But we’re still violating the DRY principle. Don’t repeat yourself.</p><p>So today I’m gonna present you with 2 techniques to either declare that variables in CSS and use them from JS, or viceversa.</p><h3>JS =&gt; CSS</h3><p>So you’re decided to use JavaScript as your source of truth. It’s OK, you have your reasons. For instance, you’re maybe loading these constants from a npm package, they’re exported as JS constants and you need to inject them into the CSS.</p><p>So first, you need to have a method of injecting CSS from your code. Here’s a function for that:</p><pre>function <strong>addStyle</strong>(styleString) {<br>  const style = document.createElement(<em>&#39;style&#39;</em>);<br>  style.textContent = styleString;<br>  document.head.append(style);<br>}</pre><p>This function receives a parameter styleString, that will be the CSS we want to inject. The first line of the function creates a &lt;style&gt; element, the second one sets the content of that element to the styleString parameter, and the last one appends that element to the &lt;head&gt; portion of our HTML. That’s it.</p><p>Once you have that function, you can call it with the standard declaration of a CSS variable.</p><pre><strong>addStyle</strong>(<em>`<br>  :root {<br>    --color-primary: </em>${<strong>primaryColor</strong>};<em><br>  }<br>`</em>)</pre><p>Great! So now you can access that variable from the CSS!</p><pre>button {<br>  background: var(--color-primary);<br>}</pre><p>That’s it! Easy, right?</p><p>This method has one <strong>caveat</strong>, though. The CSS now depends on the JS being loaded and executed. Why is this important? Typically, the CSS is the first thing you load of a page, and the JS is the last. You may already have that issue, if you use CSS-in-JS for instance, but it’s good to keep it in mind.</p><p>Here’s a codepen with an example to play!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsmvilar%2Fembed%2Fpreview%2FLYGKvqq%3Fheight%3D600%26slug-hash%3DLYGKvqq%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsmvilar%2Fpen%2FLYGKvqq&amp;image=https%3A%2F%2Fassets.codepen.io%2F380485%2Finternal%2Fscreenshots%2Fpens%2FLYGKvqq.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596154050%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/48fcb6df894d72d5362cb275d35b9fb9/href">https://medium.com/media/48fcb6df894d72d5362cb275d35b9fb9/href</a></iframe><h3>CSS =&gt; JS</h3><p>This is a handy way to access your CSS variables from the JavaScript code.</p><p>This method relies in the following code snippet:</p><pre>function <strong>getCSSVariable</strong>(varName) {<br>  return getComputedStyle(document.documentElement)<br>    .getPropertyValue(varName);<br>}</pre><p>This function receives the name of the variables as a parameter and does the following: first, it calls <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle">window.getComputedStyle</a> for the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement">document.documentElement</a> (this is typically the &lt;html&gt;), this returns a CSSStyleDeclaration, from where we can call getPropertyValue and get the variable we want.</p><p>Here’s a codepen with an example of this technique to play too:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsmvilar%2Fembed%2Fpreview%2FOJMeGGM%3Fheight%3D600%26slug-hash%3DOJMeGGM%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fsmvilar%2Fpen%2FOJMeGGM&amp;image=https%3A%2F%2Fassets.codepen.io%2F380485%2Finternal%2Fscreenshots%2Fpens%2FOJMeGGM.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596154018%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2302c8332cc33ad28ced87401d35d57/href">https://medium.com/media/e2302c8332cc33ad28ced87401d35d57/href</a></iframe><h3>What about preprocessors?</h3><p>These techniques both rely in the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties">CSS variables</a> feature, so if you’re using SASS/LESS/Stylus variables, they won’t work.</p><p>You could, however, declare CSS variables from the preprocessor variables and then obtain them from JS, like in this next example using SASS:</p><pre>$red: #ff0000;</pre><pre>:root {<br>  --red: $red;<br>}</pre><p>Maybe you can even write a cool function/mixin to generate that code in a meta-programming style. Super cool, huh.</p><p>I hope you find these techniques useful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40efd253a945" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/stop-duplicating-constants-between-js-and-css-40efd253a945">Stop duplicating constants between JS and CSS</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Sails sockets using Jest]]></title>
            <link>https://medium.com/@smvilar/testing-sails-sockets-using-jest-f85b4a882fd?source=rss-14f56fc78735------2</link>
            <guid isPermaLink="false">https://medium.com/p/f85b4a882fd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[sailsjs]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[Santiago Vilar]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 16:14:47 GMT</pubDate>
            <atom:updated>2020-06-21T23:43:55.536Z</atom:updated>
            <content:encoded><![CDATA[<p>This was quite a horror story for me, so I decided to write a guide to help you if you’re stuck in this situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ys2F0pB1QmyTiVa-" /><figcaption>Photo by <a href="https://unsplash.com/@senseiminimal?utm_source=medium&amp;utm_medium=referral">Sensei Minimal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The problem</h3><p>I need to test socket functionality to make sure some messages are received and get sent when certain conditions happen.</p><p>Specifically, there’s a bug in production where <strong>a message that <em>should</em> arrive, doesn’t arrive</strong>, and it’s especially hard to reproduce, so making a test case scenario for this bug is an advantage to solve it right, and then prevent future regressions.</p><blockquote><em>Want to read this story later? Save it in </em><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=blog&amp;utm_campaign=noteworthy&amp;utm_content=eid7"><em>Journal</em></a><em>.</em></blockquote><h3>Tools</h3><p>This web app uses <a href="https://github.com/balderdashy/sails.io.js">Sails</a> to handle requests and sockets.</p><p>Sails uses <a href="https://github.com/socketio/socket.io-client">SocketIO</a> behind the scenes, and I found this library <a href="https://github.com/romgain/jest-websocket-mock">jest-websocket-mock</a> which in turn uses <a href="https://github.com/thoov/mock-socket">mock-socket</a> that includes a way to mock SocketIO, so it should be easy!</p><pre>npm install --dev jest-websocket-mock</pre><p>Spoiler alert: it doesn’t work right out of the box.</p><p>Each layer of abstraction <a href="https://twitter.com/smvilar/status/1042076875600945159/photo/1">adds complexity</a> when trying to understand why the code behaves in a certain way. So I dive in the Sails source code to understand where it fails, and I find out that Sails uses some functionality of SocketIO that’s not mocked by mock-socket, specifically socket.io.engine.transport.on, socket.once and socket.connected (I don’t blame Sails on this, SocketIO API is quite a mess, frankly) so I provide the additional mock for Jest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37e3cec9d52a99219d149e202966b15/href">https://medium.com/media/c37e3cec9d52a99219d149e202966b15/href</a></iframe><p>Let me explain what’s going on there:</p><ol><li>The file needs to be in test/__mocks__/socket.io-client.js so Jest picks it up as the module mock when importing socket.io-client.</li><li>We extend the mock-socket SocketIO mock implementation. Make sure to also install the dependency: npm i -D mock-socket</li><li>We add a once method that it’s just an alias for the on (yeah, the behaviour should be different, I know, but it doesn’t matter in my test scenarios and it’d just add clutter at this point)</li><li>We define socket.io.engine.transport.on as a mock function.</li><li>We define the property connected to just be a getter returning the socket.readyState === 1 (in this case, I find important to try to replicate the behaviour of the connected property)</li></ol><p>OK, so now that is mocked and ready to go. 🤞</p><h3>Writing the test</h3><p>This part is pretty straight-forward (now, that we solved the getting-right-the-mock part).</p><pre><em>import</em> WS <em>from</em> &#39;jest-websocket-mock&#39;</pre><p>We import thejest-websocket-mock module. This module works by creating a <strong>websocket mock server</strong>.</p><p>In order to use it we need to add:</p><pre>let mockServer;</pre><pre>beforeEach(() <strong>=&gt;</strong> {<br>  mockServer <strong>=</strong> <strong>new</strong> WS(API_URL);<br>});</pre><pre>afterEach(() <strong>=&gt;</strong> {<br>  WS<strong>.</strong>clean();<br>});</pre><p>This will tell Jest to initialise the mock server before each test, and clean it afterwards. You could also write it as:</p><pre>let server;</pre><pre>beforeEach(() <strong>=&gt;</strong> {<br>  WS.clean();<br>  server <strong>=</strong> <strong>new</strong> WS(API_URL);<br>});</pre><p>Which I think is more concise, but it’s up to you.</p><p>So now if you can use the mock server as the <a href="https://www.npmjs.com/package/jest-websocket-mock">jest-websocket-mock README</a> says:</p><pre>// real clients can connect<br>const client = new WebSocket(&quot;ws://localhost:1234&quot;);<br>// wait for the server to have established the connection<br>await server.connected;<br> <br>// the mock websocket server will record all the messages<br>// it receives<br>client.send(&quot;hello&quot;);<br> <br>// the mock websocket server can also send messages to all<br>// connected clients<br>server.send(&quot;hello everyone&quot;);<br> <br>// ...simulate an error and close the connection<br>server.error();<br> <br>// ...or gracefully close the connection<br>server.close();</pre><p>So that’s it! I hope this article helps you write more solid and secure websocket applications. 💪</p><p>📝 Save this story in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f85b4a882fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Cypress with Cucumber to test your app as if you were a user]]></title>
            <link>https://levelup.gitconnected.com/using-cypress-with-cucumber-to-test-your-app-as-if-you-were-a-user-15288900a1a6?source=rss-14f56fc78735------2</link>
            <guid isPermaLink="false">https://medium.com/p/15288900a1a6</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[cypressio]]></category>
            <category><![CDATA[cucumber]]></category>
            <category><![CDATA[end-to-end-testing]]></category>
            <dc:creator><![CDATA[Santiago Vilar]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 14:39:40 GMT</pubDate>
            <atom:updated>2020-08-04T02:13:04.493Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to write automated end-to-end tests that resemble the way your users navigate your application</h4><p>Wouldn’t it be great if you could just write <strong><em>“Given I log into the app, when I click the settings icon, then I see the settings menu and I see my name on it”</em></strong>? In this post I’ll guide you through the tools you need and the steps you should follow to achieve this kind of testing.</p><h3>Meet Cypress</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ckM24GNp_o-BRfGp.png" /><figcaption>screenshot from cypress website</figcaption></figure><p>If you haven’t heard of <a href="https://www.cypress.io/">Cypress</a>, it’s the current <em>hot thing</em> to write end-to-end tests. It replaces Selenium and greatly improves the developer’s experience of writing tests. You install it as a simple npm package (npm install -D cypress), and run it with a simple command (npx cypress open). It’s also distributed as a Docker image, so you can even test your application inside a container for better consistency.</p><h3>So, what’s a cucumber?</h3><p>No, not this one 🥒.</p><p><a href="https://cucumber.io/">Cucumber</a> is a test framework for <a href="https://en.wikipedia.org/wiki/Behavior-driven_development">BDD</a>. By using the <a href="https://cucumber.io/docs/gherkin/reference/">Gherkin</a> language, it allows you to write tests that look like <a href="https://en.wikipedia.org/wiki/Natural_language">natural language</a>. It’s not magic though, it relies on you writing <a href="https://cucumber.io/docs/cucumber/step-definitions/">step definitions</a> for each new step you declare. Step definitions are the way you translate plain English (“I press the Submit button”) into JavaScript (cy.find(&quot;Submit&quot;).click()).</p><p>You can even write the tests <a href="https://cucumber.io/docs/gherkin/reference/#spoken-languages">in your own spoken language</a>!</p><h4>Advantages</h4><ul><li>You can easily share your tests with non-technical teammates, clients, stakeholders to show how the app behaves under specific conditions.</li><li>When feature requests arrive, you can almost seamlessly translate them to a Cucumber test right away and start developing!</li></ul><h3>Setting your testing environment</h3><p>To start, you’ll need to install Cypress and the <a href="https://github.com/TheBrainFamily/cypress-cucumber-preprocessor">Cucumber preprocessor</a>:</p><pre>npm i -D cypress cypress-cucumber-preprocessor</pre><p>Then you need to setup Cypress to start reading your feature files. In cypress.json, add:</p><pre>{<br>  &quot;baseUrl&quot;: &quot;http://localhost:8080&quot;,<br>  <strong>&quot;testFiles&quot;: &quot;**/*.{feature,features}&quot;</strong><br>}</pre><p>(The baseUrl should be set to wherever is your application running)</p><p>Once you’ve got that, you’ll also need to configure the cypress-cucumber-preprocessor to stop using global step definitions (they promise this will be default in the future). In your package.json, you’ll need to add:</p><pre>&quot;cypress-cucumber-preprocessor&quot;: {<br>  &quot;nonGlobalStepDefinitions&quot;: true<br>}</pre><p>And that’s it! Let’s move to the tests.</p><h3>Writing your first test</h3><p>There are several stuff you need to understand to start writing tests using this combination of Cypress and Cucumber. I’ll try to guide you through your first test to introduce you to the new concepts (Cypress commands, step definitions, Cucumber expressions, etc).</p><p>Let’s assume you have a Login page in your app, and it looks like this:</p><figure><img alt="A simple login screen with email and password inputs and a Login button" src="https://cdn-images-1.medium.com/max/1024/1*OuVtc2cTOVCPAxndFefO4Q.png" /></figure><p>Let’s also assume that you already have a development environment with a seeded database with an existing user user@example.org with a known password.</p><p>We want to test if the app handles login OK. Let’s first write this test as if we’re using just Cypress:</p><pre>cy.visit(&#39;/login&#39;)<br>  .findByPlaceholder(/email/)<br>  .type(&#39;user@example.org&#39;)<br>  .findByPlaceholder(/password/)<br>  .type(&#39;this is my password&#39;)<br>  .findByText(&#39;Log in&#39;)<br>  .click()<br>  .url()<br>  .should(&#39;eq&#39;, &#39;/&#39;)<br>  .window()<strong>.</strong>its(&#39;localStorage.email&#39;)<br>  .should(&#39;eq&#39;, &#39;user@example.org&#39;)</pre><p>(Note: I’m using <a href="https://github.com/testing-library/cypress-testing-library">cypress-testing-library</a> to write the DOM queries, I recommend that you do the same to enforce better practices)</p><p>This test is pretty straight-forward: it navigates to /login (using the baseUrl you set in the cypress.json), it fills the username and the password and clicks the “Log in” button. Then it checks that the url is the root of the app / and the email of the logged user is in the localStorage.</p><p>In Cypress you can group multiple commands into a single custom command for easier reuse and tidier tests. In order to do that, we need to create a file called cypress/support/commands.js and add:</p><pre>Cypress.Commands.add(&#39;loginWith&#39;, ({ email, password }) =&gt;<br>  cy.visit(&#39;/login&#39;)<br>    .findByPlaceholderText(/email/)<br>    .type(email)<br>    .findByPlaceholderText(/password/)<br>    .type(password)<br>    .findByText(&#39;Log in&#39;)<br>    .click()<br>)</pre><p>And then open cypress/support/index.js and add:</p><pre>import &#39;./commands&#39;</pre><p>Once you do that, you can use the custom command in the tests:</p><pre>cy.loginWith({<br>  email: &#39;user@example.org&#39;,<br>  password: &#39;this is my password&#39;<br>})<br>  .url()<br>  .should(&#39;eq&#39;, &#39;/&#39;)<br>  .window()<strong>.</strong>its(&#39;localStorage.email&#39;)<br>  .should(&#39;eq&#39;, &#39;user@example.org&#39;)</pre><h4>Translate to Gherkin</h4><p>Having that test in mind, we need to figure out how we want to write it in the Cucumber language, Gherkin. I recommend trying how it feels more natural, without thinking about how it translates to the underlying code. Create a cypress/integration/login.feature file and write:</p><pre>Feature: Login</pre><pre>Scenario:<br>  When I login<br>  Then the url is /<br>  And I&#39;m logged</pre><p>In this particular test I skipped the Given stage since it’s not useful (Given I open the app?).</p><p>Note we defined 3 steps: ‘I login’, ‘the url is {word}’, and ‘I’m logged’. So we need to create 3 step definitions. In order to do so, create a js file inside a directory <strong>named as the feature file</strong> (login/login.js) and write:</p><pre>import { When, Then } from &#39;cypress-cucumber-preprocessor/steps&#39;</pre><pre>When(&#39;I login&#39;, () =&gt; {<br>  cy.loginWith({ email: &#39;user@example.org&#39;, password: &#39;this is my password&#39;})<br>})</pre><pre>Then(&#39;the url is {word}&#39;, (url) =&gt; {<br>  cy.url()<br>    .should(&#39;eq&#39;, `${Cypress<strong>.</strong>config()<strong>.</strong>baseUrl}${url}`)<br>})</pre><pre>Then(&#39;I\&#39;m logged&#39;, () =&gt; {<br>  cy.window()<strong>.</strong>its(&#39;localStorage.email&#39;)<br>    .should(&#39;eq&#39;, &#39;user@example.org&#39;)<br>})</pre><p>So that’s it! Now Cucumber knows how to translate these 3 steps to Cypress commands.</p><p>You run the tests and it goes like this:</p><figure><img alt="Cypress running the login test" src="https://cdn-images-1.medium.com/max/800/1*4z2RYdcY7kf8HOr9MgD52Q.gif" /><figcaption>Your robot running the test</figcaption></figure><p>When you run the test, the command log shows:</p><figure><img alt="Cypress command log showing the 3 steps defined in our feature file" src="https://cdn-images-1.medium.com/max/1024/1*4t7vC_lXsj3bReYxLnalGg.png" /><figcaption>Cypress command log showing the 3 steps defined in our feature file</figcaption></figure><p>You can select each command and see a snapshot of your app at that time, this is extremely useful to debug.</p><h3>Some final notes</h3><h4>Writing your tests first</h4><p>A general practice of <strong>TDD</strong> (test-driven development) is to write your tests first and then implement the stuff to make those tests pass.</p><p>My experience, although, is that with front-end development and most creative-type of development, it’s hard to foresee what kind of <strong>unit tests</strong> you’ll need ahead of the implementation.</p><p>But as it turns out, this is not my experience with <strong>end-to-end</strong> tests! As front-end developers we usually deal with complex screen flows with lots of changing state and we need to set the app in a certain state to start developing a new feature (e.g. we’re making a new drop-down menu in a settings section: for that you need to be logged-in, click the settings menu, navigate to the specific section, etc. in order to see the part of the application we need). Of course, hot-reloading helps a lot. But it fails a lot, too. Sometimes the changes we do affect the app state in a way that’s not “hot-reloadable”.</p><p>That’s were Cypress comes really handy: you can write the preconditions in your test before you start developing, and then do the actual development in Cypress itself (after all, it’s Chrome!). And it’s really easy to translate a feature request/bug report into a cucumber test, so you can actually write the whole test before you implement the whole stuff. Then you just aim for the green lights to submit your code.</p><h4>Breaking the Given/When/Then rule</h4><p>As I understand it, the core of <strong>BDD</strong> is that you should write your tests by setting the preconditions (the <strong>Given</strong> section), specifying the actions (the <strong>When</strong> statements) and then asserting the results (the <strong>Then</strong> part).</p><p>But, as stated by the Cypress Best Practices, <a href="https://docs.cypress.io/guides/references/best-practices.html#Creating-%E2%80%9Ctiny%E2%80%9D-tests-with-a-single-assertion">you shouldn’t write end-to-end tests as if you were writing unit tests</a>, since there’s a performance penalty for setting each scenario.</p><p>So what I do (and IMHO it doesn’t damage the quality of the tests) is to write a sequence of steps and assertions, for instance:</p><pre>Given I login<br><strong>Then the url is /</strong><br>When I click on Settings<br><strong>Then the url is /settings</strong><br><strong>And the auto-save toggle is set to false</strong><br>When I click on the auto-save toggle<br>Then the auto-save toggle is set to true</pre><p>Even though I could omit the intermediate assertions (marked in bold), I think this gives a better understanding of the failure, in the case this test begins to fail in an intermediate step (in this example, if it fails in the settings navigation part, I’ll have a nicer error in the Then the url is /settings assertion rather than in the I click on the auto-save toggle step.)</p><p>So, that’s it, I hope this article introduces you to the fantastic world of end-to-end testing using natural language.</p><p>I plan to write more articles about this in the future, so stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15288900a1a6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-cypress-with-cucumber-to-test-your-app-as-if-you-were-a-user-15288900a1a6">Using Cypress with Cucumber to test your app as if you were a user</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using React Context to inject dependencies to your component library]]></title>
            <link>https://levelup.gitconnected.com/using-react-context-to-inject-dependencies-to-your-component-library-9e0c4c1342da?source=rss-14f56fc78735------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e0c4c1342da</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Santiago Vilar]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 14:02:48 GMT</pubDate>
            <atom:updated>2021-07-15T03:19:33.272Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple technique for adding configuration to a React library.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cpYmsUDWGMx0bGFy" /><figcaption>Photo by <a href="https://unsplash.com/@setbydaniel?utm_source=medium&amp;utm_medium=referral">Daniel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you are writing a library that exports a set of reusable components. One of those components is a button that needs to link to another part of your app. You’re using react-router’s Link component or something similar to make these links. But you don’t want your reusable component library to have react-router as a dependency — as a matter of fact, a UI library shouldn’t be concerned with routing, right?</p><p>So you need a way to say to your Button component, “Hey, I need you to render using this base component, so you get along with the rest of my app.”</p><p>One option could be to pass a prop to this component to tell the button how it should render, for instance:</p><pre>&lt;Button {...props} renderComponent={Link} /&gt;</pre><p>and then the Button component code will be something like this:</p><pre>// Button.js<br>const Button = ({ renderComponent, ...otherProps }) =&gt; {<br>  const LinkComponent = renderComponent;<br>  return &lt;LinkComponent {...otherProps} /&gt;;<br>};</pre><p>This approach has some drawbacks, though.</p><p>The most obvious one, you need to specify the render component to each instance of Button your app needs to use. This is cumbersome but it’s not so terrible.</p><p>But, what if your component library also contains a component called NavMenu that consists of multiple Buttons, each with a link to a different part of the application? You’ll need to implement the renderComponent prop in your NavMenu component too just so it can deliver it to the underlying Button component.</p><pre>// NavMenu.js<br>const NavMenu = ({ buttonRenderComponent, urlA, urlB }) =&gt; (&lt;&gt;<br>  &lt;Button renderComponent={buttonRenderComponent} href={urlA} /&gt;<br>  &lt;Button renderComponent={buttonRenderComponent} href={urlB} /&gt;<br>&lt;/&gt;);</pre><p>This is awful and also shows a weakness in our design, the Button implementation is leaking through the NavMenu.</p><h3>Context API to the rescue</h3><p><a href="https://reactjs.org/docs/context.html">React Context API</a> is a great tool when it comes to minimizing the amount of prop-passing through the component tree. Of course, this power shouldn’t be abused, but, for our current situation, it comes <em>really</em> handy.</p><p>The steps for implementing this solution are very simple:</p><ol><li>your library needs to expose a Context, defining the initial value,</li><li>your Button component will need to consume that context and get the specified component to render from there, and</li><li>the library user will need to import the library context and provide the value in the root of the application.</li></ol><p>In JavaScript:</p><pre><strong>// library/context.js</strong><br>import { createContext } from &#39;react&#39;;</pre><pre>const LibraryContext = createContext({<br>  LinkComponent: undefined<br>});</pre><pre>export default LibraryContext;</pre><pre><strong>// library/button.js</strong><br>import React, { useContext } from &#39;react&#39;;<br>import LibraryContext from &#39;./context&#39;;</pre><pre>const DefaultLinkComponent = ({ to, ...props }) =&gt; (<br>  &lt;a href={to} {...props} /&gt;<br>);</pre><pre>const Button = (props) =&gt; {<br>  const {<br>    LinkComponent = DefaultLinkComponent<br>  } = useContext(LibraryContext);</pre><pre>  return &lt;LinkComponent {...props} /&gt;;<br>};</pre><pre><strong>// app.js</strong><br>import { BrowserRouter, Link } from &#39;react-router-dom&#39;;<br>import { Context, Button } from &#39;my-library&#39;;</pre><pre>render(<br>  &lt;Context.Provider value={{ LinkComponent: Link }}&gt;<br>    &lt;BrowserRouter&gt;<br>      &lt;Button to=&quot;/path&quot; /&gt;<br>    &lt;/BrowserRouter&gt;<br>  &lt;/Context.Provider&gt;<br>);</pre><p>Easy, right? Now you have a way to configure your component library, and more importantly, you have successfully extended your components without adding an external dependency to your toolbox.</p><h3>Additional use case: cross-platform rendering</h3><p>Maybe this approach can also help in making a cross-platform component library that can render using a different set of “primitives” depending on the Context value.</p><p>I haven’t researched it yet, but I think that it may be possible to write a library that only depends on react, and then it uses react-dom, react-native or even a <a href="https://reactpixi.org/">Canvas/WebGL rendering backend</a>, injected via the Context.</p><p>If there’s anyone out there that have already done this, please point me to the project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e0c4c1342da" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-react-context-to-inject-dependencies-to-your-component-library-9e0c4c1342da">Using React Context to inject dependencies to your component library</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>