<?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 Khang Lu on Medium]]></title>
        <description><![CDATA[Stories by Khang Lu on Medium]]></description>
        <link>https://medium.com/@khang.lu?source=rss-d1f6def09f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eO4-ogon3NDKc6EjQ4QfmA.jpeg</url>
            <title>Stories by Khang Lu on Medium</title>
            <link>https://medium.com/@khang.lu?source=rss-d1f6def09f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:53:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khang.lu/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[React at scale: Unit Testing]]></title>
            <link>https://medium.com/@khang.lu/react-at-scale-unit-testing-d1641ba50f8e?source=rss-d1f6def09f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1641ba50f8e</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Khang Lu]]></dc:creator>
            <pubDate>Mon, 10 Jul 2017 14:16:13 GMT</pubDate>
            <atom:updated>2017-07-10T14:20:54.976Z</atom:updated>
            <content:encoded><![CDATA[<p>What is unit testing in React? Why do you need it? When do you need it? With which tool? What to test and what not to. All answered here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZNtm9UZpkuZj4IM1BnLgA.jpeg" /><figcaption>Test your React component with confidence</figcaption></figure><p>An analogy I like a lot is that unit testing is like flossing. It doesn’t really give you instant gratification but in the long run it saves you time, money and helps you avoid a lot of pain.</p><h4>What is unit testing in React?</h4><p>Unit testing means to verify if a unit of your code is working as expected. It could be a React component, a function, a method, an interaction or a logical behavior. It works by <strong>verifying if your unit of code outputs the expected result given an input</strong>.</p><p>Unit tests in React are tightly coupled with the React component you wrote the test for. Thus you often see project putting tests and react component in the same folder which is a great structure to better separate your concerns.</p><h4><strong>Why do you need it?</strong></h4><p>TL,DR: Having unit test will help you and your team <strong>move much quicker</strong> in the long run. Here’s why:</p><p>First, <strong>it allows you to make big changes to the code base in a confident manner.</strong> It prevents regression issues which could potentially cost multiple hours of fixing. You don’t normally see these issue in a simple To do app. However when a React app hits a certain scale of constantly reusing and modifying a component and it’s getting harder to keep track of the changes around the code base, that’s when unit testing really shines. Here in the team building <a href="http://www.mazda.com.au,/">www.mazda.com.au</a> with a 200,000+ line React code base, unit testing allows us to move quickly with confidence.</p><p>Second, <strong>having unit tests forces you to write testable code for your React component </strong>and this is very important, I would say even more important than the first reason. It makes you produce React component with less side effect, more predictable state, better separated functionally and better readability. It also gives you better understanding of the code you wrote, you started to write code for the expected results, not just for what it does.</p><p>React itself is functional and compositional by nature which means it lay a strong foundation for writing testable code by default. It also provide developer a sufficient set of tools to deal with side effects and internal state. Yet many people abuse these tool and make (component lifecycle methods and setState for example) their app less predictable which in turn make it fragile and error-prone. Having a mindset of constantly asking “How should I test this?” is crucial in writing a new React component if you want it to be maintainable.</p><p>A popular example is people often want to do a lot of things like data fetching, mutation, logic statements in a single giant method, whether it be in the constructor, a lifecycle method or the render method. This makes the component extremely hard to write unit test for. Having the mindset of writing unit test, you can break them down into multiple functions and methods, each of them have a their own scope and responsibility, this makes writing test a walk in the park as well as contributes to a much more enjoyable development experience. This also allows every member of a big front end team to grab what’s going on much quicker when they look at components that were written by others.</p><h4>When do you need it?</h4><p>Every serious React app that involves a team and a client needs unit test.</p><p>If you are writing a simple personal project or just putting together components for educational purpose and couldn’t justify spending time writing unit test, it’s fine not to write test. Even in those situation, I would encourage you to write test just for learning purpose.</p><h4><strong>Which tool should you use</strong></h4><p><a href="https://facebook.github.io/jest/">Jest</a> and <a href="http://airbnb.io/enzyme/index.html">Enzyme</a> is rapidly becoming the defacto testing combo for React app. Jest is a JavaScript testing framework from Facebook, the creator of React themselves. Enzyme is an assertion library from AirBnB, one of the biggest adopter of React.</p><p>You can organise the test to be the same folder as your component and have Jest to run through all of them in watch mode. That way you can keep track of which test is failing when you make changes throughout the code base.</p><h4>What to test</h4><p>You don’t use Jest or any JavaScript unit testing framework to test complex UI interaction with sequence of actions, that’s the job of integration testing and usually performed by automated cross browser test runner like Selenium. What you should focus on writing test for is <strong>environment agnostic behaviour</strong>, here are some of the most common ones:</p><ol><li><a href="https://facebook.github.io/jest/docs/snapshot-testing.html">Snapshot testing with Jest</a></li><li>Function(ality) within a component</li><li>Utility methods/functions that are commonly used (e.g. higher-order components)</li><li>Things related to state (e.g. Results of state change, Redux reducers, actions)</li><li>API — test whether you get the expected data</li></ol><p>Thanks for reading. Hope you have fun writing tests and feel good looking at the green test passed (who said test doesn’t instantly gratify you again?).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1641ba50f8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An approach for less awkward end-to-end token based authentication]]></title>
            <link>https://medium.com/@khang.lu/an-approach-for-less-awkward-end-to-end-token-based-authentication-5627a9b8e59d?source=rss-d1f6def09f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5627a9b8e59d</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[token]]></category>
            <dc:creator><![CDATA[Khang Lu]]></dc:creator>
            <pubDate>Mon, 05 Jun 2017 12:24:10 GMT</pubDate>
            <atom:updated>2017-08-29T05:28:48.609Z</atom:updated>
            <content:encoded><![CDATA[<p>Micro service for authentication and how to handle token on both ends for better session management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgAzWIzQR9nXWc1rIt0Kpg.jpeg" /><figcaption>Picking out the blue lock with confident</figcaption></figure><p>Recently I have encountered a lot of questions surrounding the topic of how to implement a token based authentication using JWT. The concept of JWT is very simple, you can read more about it <a href="https://jwt.io/introduction/">here</a>. However, implementing it can get awkward very quickly. There is a lot of decisions to make as to when to issue a token, where to store it on client side, how to manage sessions while keeping the API stateless, etc. Then you might stumble on to articles like this one: <a href="http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/">Stop using JWT for sessions</a> which left you wondering if you have spent the whole week doing something worthless.</p><p>Worry not, there is an approach that is not only secured and fast but also resource-saving and accountable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*uwE16rK-eD3MxAMOPhnyeA.png" /><figcaption>Overall architecture</figcaption></figure><p>First, from your authentication service, for the initial user request you will issue <strong>two tokens</strong>: one <strong>access</strong> token and one <strong>refresh</strong> token. As their name suggest, the access token is the normal JWT that you stick in the request header on each request, the other one — the refresh token is the one used for keeping track of the session. The access token should have a <strong>short life span</strong> around 10–20 minutes. The refresh token, on the other hand, has <strong>longer life</strong> of around 2–3 hours depending on the amount of inactive period you could forgive.</p><p>The client side will hold this pair of tokens in localStorage (you might see suggestions to store tokens on sessionStorage which is usually the security requirement in many financial companies/banking websites, however it has huge usability trade-off as your session ends as soon as you close the tab). Everytime the client make a request, the access token is sent along the request header as usual. Your app then needs a <strong>middleware </strong>to redirect all requests to the authentication service.</p><p>The service then perform the validation check on the token to see if the user credentials are matched and also if they are allowed to access the resource if you have permission control set up. If the checks are all good, the service will signify the API service to make a response to the client with a <strong>new access key</strong> inserted inside. If the checks do not pass, the response will be sent back to client side with the corresponding error message.</p><p>If the error happens due to the access token expiry, the client will make a request to the authentication service to renew the token. This request will need <strong>both the old access token and the refresh token</strong> which has been sitting on the client side since the start. The authentication server will then perform all the checks to verify the authenticity and validity of both tokens as well as the user credentials before generate and send <strong>a new pair of tokens </strong>back to the client side for continuous use and start a new session. This whole process happen on the server without client noticing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*yRfL6aYGB0v2mfbl-qrOhA.png" /><figcaption>Life span of the access token</figcaption></figure><p>If the refresh token expires. Then a custom error will be sent back to signify the end of the previous session, log user out and present them the login form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*uGUW0KzlCk4SN4lZIbY2DA.png" /><figcaption>Refresh token expiry ends the session</figcaption></figure><p>The bits and pieces of implementation might be different depending on the scale and purpose of each system. The idea, however, stays the same. For the front end, if you happen to use React like I do, a higher-order component can be utilized to manage token sending, error handling and redirecting on each API request. The back end architecture can be implemented using any major back end language, authentication service can be (and better be) on its own server and separate from API services.</p><p>While preserving all the benefit of JWT authentication, this approach works great as it</p><ul><li>Keeps your API service and authentication service stateless while seamlessly implementing sessions for both browser and mobile applications.</li><li>Minimizes database access as most of the time the authentication server can validate the access token without the need of querying the database.</li><li>Allows the authentication server to log and keep track of each request and renewal operations.</li></ul><p>This approach also offers a higher level of security compare to the traditional one token system. It mitigates the risk of a long-lived token living in the client side being compromised which is a single point of failure. In case of the access token being compromised, the attack-able window is much shorter. Refresh token being exposed is even less of a problem as it is completely useless on its own.</p><p>Thanks for reading! If you have any question, suggestion, objection or anything please feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5627a9b8e59d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript ES6 for React: Function that returns another function]]></title>
            <link>https://medium.com/@khang.lu/javascript-es6-for-react-function-that-returns-another-function-66481f19bbf7?source=rss-d1f6def09f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/66481f19bbf7</guid>
            <category><![CDATA[higher-order-components]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Khang Lu]]></dc:creator>
            <pubDate>Sun, 26 Mar 2017 05:26:43 GMT</pubDate>
            <atom:updated>2017-08-29T05:29:18.787Z</atom:updated>
            <content:encoded><![CDATA[<h4>From currying in JavaScript to React higher-order component.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrRSyt6LIup2-M7m92Tntg.png" /></figure><p>I started picking up React in the post ES6 era and while reading through different React code bases, these are the two things that confuse me the most:</p><ol><li>Chaining of ES6 arrow functions. For example: <br>const chainedAddition = a =&gt; b =&gt; console.log(a+b) (*)</li><li>Pairs of parentheses next to each other, frequently seen in React higher-order components signature: <br>const Batman = connect(money, moreMoney)(BruceWayne)</li></ol><p>Those are the examples of functions that return another function. Here is my attempt for an explanation in simple terms for fellow JavaScript starters which happen to stumble upon this article.</p><p>(*) For those who are not familiar with ES6, these 3 function declarations are equal</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b675e3f1f3c82e2baca8deeb8a5dde9/href">https://medium.com/media/7b675e3f1f3c82e2baca8deeb8a5dde9/href</a></iframe><h3>Example 1: Currying</h3><p>Currying is transforming a function with N number of parameters into a chain of N functions, each with one parameter. The resulting function is calledcurried function .</p><p><a href="https://en.wikipedia.org/wiki/Currying">Currying</a> is named after <a href="https://en.wikipedia.org/wiki/Haskell_Curry">Haskell Curry</a>, an American mathematician and logician. It is a technique used not only in programming but also in mathematics and computer science.</p><p>Here we use currying in JavaScript as an example to demonstrate a function that returns another function. A dead simple code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f55e39ffa0dfbd4a0cef8324a6f185/href">https://medium.com/media/e8f55e39ffa0dfbd4a0cef8324a6f185/href</a></iframe><p>In the code snippet above, addCurried is a curried function , it’s a function that returns another function, the exact same one we used at the starting example.</p><p>As you can see, we can execute a curried function by providing pairs of parentheses one after another to invoke each level of the chained function.</p><p>Breaking it down, addCurried(1)(2) equals</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cad2cb3b5b830478fd4ceda66ad8a2a1/href">https://medium.com/media/cad2cb3b5b830478fd4ceda66ad8a2a1/href</a></iframe><h3>Example 2: React higher-order component</h3><p>A React HOC takes a component, enhances it, then returns the enhanced component.</p><p>Let’s bring back our starting example:</p><p>const Batman = connect(money, moreMoney)(BruceWayne)</p><p>Yes, you’re right, connect(money, moreMoney) is a function that returns a function. That returned function is the enhancer, it then takes BruceWayne — a React component — as parameter. The result is Batman.</p><p>Exactly like addCurried isn’t it? That’s how a chain of functions works.</p><p>And that’s it for “function-ception”. This is a key concept in JavaScript and React which is functional and composable by nature. I hope you learned something new and are more confident now to explore those React code bases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66481f19bbf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>