<?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 Jason Lai on Medium]]></title>
        <description><![CDATA[Stories by Jason Lai on Medium]]></description>
        <link>https://medium.com/@LaiJase?source=rss-7a0f2b42dba5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*TWgCTVIP2T3pWbFN.jpg</url>
            <title>Stories by Jason Lai on Medium</title>
            <link>https://medium.com/@LaiJase?source=rss-7a0f2b42dba5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:46:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@LaiJase/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[Understanding dependency management with Node Modules]]></title>
            <link>https://levelup.gitconnected.com/understanding-dependency-management-with-node-modules-1c47bcdee98b?source=rss-7a0f2b42dba5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c47bcdee98b</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[yarn]]></category>
            <dc:creator><![CDATA[Jason Lai]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 23:14:41 GMT</pubDate>
            <atom:updated>2021-01-17T23:20:23.579Z</atom:updated>
            <content:encoded><![CDATA[<h4>How version control in your package.json works and how the lock file can prevent breaking changes to your application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9O8gxysDIhl6oaG" /><figcaption>Photo by <a href="https://unsplash.com/@marcello54?utm_source=medium&amp;utm_medium=referral">Marcello Gennari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The rise of JavaScript modules has led to much more complex tooling to manage script files. Most modern web applications now use module bundlers like <a href="https://webpack.js.org/">webpack</a> to leverage the benefits of JavaScript modules and more complex libraries such as <a href="https://reactjs.org/">React</a>, instead of using simple task runners like <a href="https://gulpjs.com/">Gulp</a> to transpile and concatenate assets.</p><p>This has created an entirely new set of challenges for JavaScript developers, including dependency management. There is a common term in the tech community known as <em>dependency hell </em>— referring to the challenges and difficulties that arise from having packages with shared dependencies of different or incompatible versions.</p><p>Some common issues I have seen developers face with node modules are often related to a lack of understanding of how version control and package resolution works with <a href="https://www.npmjs.com/">Node Package Manager</a>. This could be accidentally upgrading a package which introduces a breaking change, not understanding how to resolve duplicate or conflicting dependencies, not knowing how to resolve merge conflicts in the lock file, and the ultimate offence — deleting the lock file.</p><h4>What are JavaScript Modules?</h4><p>JavaScript modules are simply script files which can be loaded into each other to share functionality. One of the main benefits of modules are that they allow us to break down large scripts into smaller, reusable self-contained pieces of code.</p><p>A module or a collection of modules can be published as a <em>package</em> to a public or private registry for consumption. The main public registry for JS modules is <a href="https://www.npmjs.com/">Node Package Manager</a> (NPM). This has facilitated the growth of the JS community by enabling developers to share code globally.</p><p>Packages can be installed in projects on your local machine using a command line package manager such as <a href="https://github.com/npm/cli">npm</a> or <a href="https://classic.yarnpkg.com/en/docs/install#mac-stable">yarn</a> and are added to a node_modules folder in your project root.</p><h4>What is the package.json and lock file?</h4><p>The package.json and lock file (yarn.lock if you are using yarn, package-lock.json if you are using npm) are configuration files that tell the installer which versions of the packages to install.</p><p>Think of the package.json as the <em>specification</em> — it lists all the packages and their version requirements (e.g. minimum version, maximum version, etc). When you install your packages for the first time, a lock file is created. Think of this as the <em>contract </em>— it has a list of the exact versions of packages that met the specification in the package.json <em>at the time they were first installed</em>.</p><p>Typically a project does not exist solely on a single developer’s machine, the repository is cloned and installed by many developers or even in a CI/CD pipeline, therefore it is important to ensure packages are properly version controlled — which is the role of the lock file. Any time modules are subsequently installed, the installer will use the version specified in the lock file, <em>not</em> the package.json.</p><p>If you’re not familiar with how module resolution with package managers works, if you run into an installation problem you might be tempted try deleting everything (including the lock file) and installing again, but you should <em>never delete the lock file </em>as this can introduce breaking changes by accidentally upgrading dependencies. To better understand this you need to know how <a href="https://semver.org/">semantic versioning</a> (semver) is used in the package.json.</p><h4>Semver 101</h4><p>Version numbers in semver consist of 3 sets of numbers separated by a ., for example 1.2.3 which represent major.minor.patch respectively. The <a href="https://semver.org/">semver documentation</a> explains each of these:</p><pre>1. MAJOR version when you make incompatible API changes,<br>2. MINOR version when you add functionality in a backwards compatible manner, and<br>3. PATCH version when you make backwards compatible bug fixes.</pre><p>In the package.json, for each dependency you will see a corresponding semver number. Sometimes this is prefixed with a carat ^ or tilde ~.</p><ol><li>^1.2.3 — install the latest version of 1.X.X (don’t go past specified major, only a higher minor and patch number).</li><li>~1.2.3 — install the latest version of 1.2.X (don’t go past specified major or minor, only a higher patch number).</li></ol><p>You can use <a href="https://docs.npmjs.com/cli/v6/using-npm/semver#ranges">range operators</a> (e.g. &gt;=) if you need more fine tuned control of the version range.</p><h4>How deleting the lock file can affect version control</h4><p>Imagine our project has a dependency, example-package at version ^1.0.0. This is the latest available version at the time of first install and is added to the lock file as 1.0.0. A month later, a new release of example-package comes out 1.1.0. Let’s pretend a new developer joins your team and clones the project repository, and installs the project.</p><p>The version in the package.json is ^1.0.0 (meaning the latest 1.X.X), so you would think that the 1.1.0 would be installed on the new developer’s machine, but this is not the case. When the dependency was first added to the project, 1.1.0 did not exist, so the version listed in the lock file is 1.0.0. Therefore 1.0.0 will always be installed, despite there being a newer available version that meets the semver specification in the package.json.</p><p>If you do not commit the lock file to your repository, or delete the lock file and reinstall your node modules, then version 1.1.0 of example-package will be installed, since it will be treated as if this is the first time installing. New bugs could have been introduced into 1.1.0, or the maybe the package dependencies changed and are incompatible with other dependencies in your project.</p><p>This is how deleting the lock file can unintentionally cause dependencies to be upgraded which can break your application.</p><h4>Version Pinning</h4><p>You might think that simply removing the ^ or ~ from your version number to specify the exact version of the dependency will fix this problem. Unfortunately, even if you explicitly put the exact version of each dependency in your package.json, without a lock file you can still accidentally upgrade dependencies of dependencies.</p><p>Remember that packages are simply JavaScript modules and can interchange functionality, meaning they can import and utilise modules from other packages. Therefore, the lock file does not only handle the version control of our dependencies listed in our package.json, but all packages in the <em>dependency tree</em>. In the example below, example-package has a dependency foobar in its own package.json, at version ^1.0.0, and foobar has its own dependency, fizzbuzz at ~1.0.0.</p><pre>// Hierarchal representation of dependency tree</pre><pre>root<br>└─┬ example-package@1.0.0<br>  └─┬ foobar@^1.0.0<br>    └── fizzbuzz@~1.0.0</pre><p>Even if we pin the version of example-package, we’ll still run into the same accidental upgrade problem with foobar and fizzbuzz since a newer version could be released which has a bug in it, and their semver numbers are not version pinned.</p><p>Without a lock file, the package manager will update any dependencies of dependencies and their dependencies and so forth, which could introduce breaking changes.</p><h4>Handling duplicate or conflicting package versions</h4><p>Some packages like <a href="https://www.npmjs.com/package/react">React</a> require that only one version is installed and will throw an error if multiple versions are present. If you have two different packages in your project and each has a different version of React as a dependency, you could end up with two different versions of React installed.</p><p>You can inspect the dependency tree by using the commands yarn why or npm ls followed by the package name (e.g. yarn why example-package). I personally prefer npm ls as it provides a visual representation of the dependency hierarchy.</p><p>If there is a common version that meets the semver specified in the package.json, yarn will automatically dedupe on install and resolve to the common version. If you are using npm, you need to run <a href="https://docs.npmjs.com/cli/v6/commands/npm-dedupe">npm dedupe</a>.</p><p>If the installer cannot find a common version, then you will need to specify which version should be used. In your package.json add a resolutions field to specify the dependency and the version that should used. The version in each of the two packages will be overridden by the version in your resolutions field when you yarn install.</p><pre>// Example of resolutions field in the package.json</pre><pre>{<br>  ...<br>  resolutions: {<br>    react: &quot;17.0.1&quot;<br>  }<br>}</pre><p>Although npm does not have an equivalent of resolutions in yarn, you can specify the version by using a pre-install hook with this package, <a href="https://www.npmjs.com/package/npm-force-resolutions">npm-force-resolutions</a>.</p><p>Resolutions are incredibly useful, and can be used not only to dedupe packages, but to fix any issues where the version of a sub-dependency could be causing a problem. For example, a package might have a dependency which has a security vulnerability, you can use the resolutions field in the package.json to force it to update to a version where this is fixed.</p><h4>Conflict resolution in the lock file</h4><p>Another issue I’ve seen is confusion around how to resolve conflicts in the lock file when merging branches, especially if not all developers are on your project are JavaScript developers or used to working with yarn, npm or node modules. This can be frustrating for them as it can block their workflow if they need to sync branches.</p><p>When multiple git branches modify the dependencies (e.g. adding new dependencies required for a new feature), it is likely to introduce a conflict in the lock file. This is perfectly normal and both yarn and npm actually make resolving conflicts quite simple.</p><p>First, always resolve the conflicts in the package.json and do <em>not</em> manually edit the lock file. In fact, there is a warning in the yarn.lock stating not to manually edit it. If you have not made any changes to the dependencies in your branch (e.g. added a new dependency, or explicitly upgraded one), then you should take the changes from the destination branch. Then, simply run yarn to run the package installer, this will automatically fix all conflicts in the yarn.lock. If using npm, run npm install --package-lock-only to do the same thing. Then, stage the package.json and lock file, and continue merging your branch with git merge --continue.</p><h4><strong>Updating and removing unused dependencies</strong></h4><p>Good housekeeping is a key part of dependency management. You should update your dependencies regularly in order to keep up to date with the latest security fixes, but this needs to be done carefully and safely to prevent breaking your application.</p><p>I’ve seen projects where dependencies have not been updated in years, and the upgrade process to address all the security vulnerabilities was incredibly painful and introduced a lot of breaking changes.</p><p>You can check which packages are out of date with the command yarn outdated or npm outdated, however do not install the latest version of these all at once. Here are some tips on how to safely upgrade your dependencies.</p><ol><li>Only upgrade one package or a group of related packages which rely on each other (e.g. React and ReactDOM) at a time on a feature branch. If your application breaks, it will be much easier to identify which package is the offender and the pull request can easily be reverted.</li><li>Ensure your application has sufficient test coverage. If you run your test suite against your pull requests in your CI/CD pipeline you can automatically catch breaking changes on the feature branch where the dependency was upgraded.</li><li>Use an automated dependency manager. Services like <a href="https://snyk.io/">Snyk</a>, <a href="https://dependabot.com/">Dependabot</a>, and <a href="https://greenkeeper.io/">Greenkeeper</a> can be added to your CI/CD pipeline. The bot will automatically checkout a new branch and raise a pull request to upgrade out of date dependencies or dependencies with known security vulnerabilities.</li></ol><p>You should also remove unused dependencies as these can free up space and improve install times, which will be more efficient for your application build process. <a href="https://github.com/depcheck/depcheck">Depcheck</a> is a great tool which will analyse your project and identify the dependencies in your package.json which are missing or unused.</p><h4>Conclusion</h4><p>Version control with NPM packages is important in maintaining the stability of your application.</p><p>Upgrading dependencies should be done intentionally and systematically to keep up to date with the latest security fixes, not accidentally by deleting the lock file. I’ve heard horror stories about applications breaking from developer friends that work at companies where the lock file is deleted in the CI/CD pipeline, or is not committed to the repository.</p><p>Understanding semantic versioning and how the package manager resolves versions using the package.json and lock file is crucial to good dependency management and will help prevent you from making these common mistakes which can introduce breaking changes into your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c47bcdee98b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-dependency-management-with-node-modules-1c47bcdee98b">Understanding dependency management with Node Modules</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[Improve Accessibility in Your React App By Managing Focus in Mutable Content]]></title>
            <link>https://medium.com/swlh/improve-accessibility-in-your-react-app-by-managing-focus-in-mutable-content-4ddf4ed92186?source=rss-7a0f2b42dba5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ddf4ed92186</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[a11y]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[accessibility]]></category>
            <dc:creator><![CDATA[Jason Lai]]></dc:creator>
            <pubDate>Fri, 09 Oct 2020 12:44:09 GMT</pubDate>
            <atom:updated>2021-06-11T13:44:55.239Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop losing focus!</h4><h4>Leverage the component “lifecycle” with useEffect to set the active element in the DOM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TzeY6MTjVC0KnL7e" /><figcaption>Photo by <a href="https://unsplash.com/@untodesign_?utm_source=medium&amp;utm_medium=referral">Daniel Ali</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When building user interfaces we follow a design, making assumptions about how the user will interact with the frontend. We display data in a certain way, provide buttons to be clicked, and update the UI according to state changes.</p><p>For accessibility, especially with interactive UI, you should not only consider what the user sees, but what a screen reader “sees” too. This is important since the screen reader will communicate to the user how to use your application. If the screen reader can’t correctly interpret your frontend, then most likely the person using it won’t either.</p><p>With mutable content, building accessible UI becomes more complex and is not just a matter of using semantic HTML. By mutable content, I mean content that can be changed in some way, usually with CRUD operations (create, read, update, delete). While dynamic changes to the UI can be announced with <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions">ARIA live regions</a>, I have found that focus handling is often missed.</p><h3>The Problem</h3><p>Imagine you are navigating through a mutable list, this could be a social feed, comments in a discussion thread, or even the items in your online shopping basket. What happens when you delete an item? The element you were focused on is suddenly no longer in the DOM, so document.activeElement will shift back to the &lt;body&gt; element. This means the user has to navigate through the entire page again to get back to where they were. You can imagine how annoying this is for users who use assistive technology or keyboard navigation.</p><p>You can check the current active element in the DOM using the chrome devtools by going to <strong><em>Console &gt; Create Live Expression</em></strong> (the eye icon) and typing document.activeElement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*l-ZLVkCQ7vtDCMrxvtqs6A.png" /></figure><p>In React web applications, programatically changing the active element is surprisingly easy to handle. I admit when looking for a solution to this problem I went down several over complicated routes until I realised the obvious — with <a href="https://reactjs.org/docs/refs-and-the-dom.html">React refs</a> I had access to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node">Node API</a>.</p><h3>The Solution</h3><h4>An example with a TypeScript Todo List App</h4><p>We can illustrate a solution to this problem with a simple todo list. In the gist below, we have a React app that stores an array of todos in state, and iterates through them to render each one with a ListItem component. There is a &lt;form&gt; to add todos, and a function to delete todos which is passed to the ListItem.</p><p>For accessibility, I’ve added some state to manage the display of the application status which will notify the user when the list has been modified. This can be <a href="https://www.a11yproject.com/posts/2013-01-11-how-to-hide-content/">hidden visually with css</a> if it is not part of the design, but can still be accessible to screen readers. The role=&quot;status&quot; attribute implicitly applies the aria-live value of polite, meaning it will wait until the user has stopped what they are doing before making the announcement, as to not interrupt them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb54b9b8c24c2dc8fd53db2266e8b4e8/href">https://medium.com/media/bb54b9b8c24c2dc8fd53db2266e8b4e8/href</a></iframe><h4>Handling Focus</h4><p>When an item is deleted from the list, we need to prevent the document.activeElement from shifting back to the &lt;body&gt; so the user doesn’t have to start over. Before we can do this, we need to define the expected behaviour and any edge cases. In the context of this application, I think it makes the most sense that when a todo is deleted, it should:</p><ol><li>Shift focus to the next todo.</li><li>If there is no next todo (e.g. it is the last in the list), it should shift focus to the previous todo.</li><li>If there is no previous todo, it should shift focus to the parent element.</li></ol><p>In the case 3, it may be tempting to programatically focus the user back to the create todo &lt;input&gt; since there are no more todos in the list. Although you could do this, I don’t believe you should. I am a firm believer in letting the user decide where to navigate, with a few exceptions (e.g. changing focus to when a modal dialog is triggered). Suddenly changing focus to somewhere completely different on the DOM can be very confusing. Even as a sighted user I despise sites that hijack my scroll or force me to navigate to places without my consent. Remember, the goal here is simply to help the user maintain their current place in list when entries are deleted, not to force them down a user flow.</p><p>In our ListItem component, we can use a ref to access the DOM Node created in the component render. Since the ref is a DOM Node, it means we have access to all the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node">Node API</a> properties and methods, including nextElementSibling, previousElementSibling, and parentElementNode.</p><p><strong>Note: </strong>unlike nextSibling, previousSibling, and parentNode, nextElementSibling, previousElementSibling, and parentElementNode will return an HTML Element or null whereas the former could return other node types such as a Document Node or Text Node.</p><p>To set the document.activeElement when a todo is deleted, we can use the useEffect hook’s cleanup function, as it will execute when the component is unmounted. We also need to add a tabindex to the elements we are going to call focus() on to ensure that we can programatically focus on them to set the document.activeElement. Since &lt;ol&gt; and &lt;li&gt; are not natively focusable elements like &lt;button&gt; or &lt;a&gt; I’m applying a tabindex of -1. This means its not focusable through sequential keyboard navigation, but it can still be programatically focused to be set as the document.activeElement so that the user does not loose their place while going through the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/387ad0c522c662a02b14e9a1d378ccab/href">https://medium.com/media/387ad0c522c662a02b14e9a1d378ccab/href</a></iframe><h4>Common mistakes</h4><p>When writing your cleanup function, it may be tempting to store the nextElementSibling and previousElementSibling in a variable, especially if you are using them in the code more than once (which I am doing in the example). This can cause the focus management to not work properly as it will give you the sibling element at the time your cleanup function is defined (on component mount), not at the time that the cleanup function is executed. This means you may be trying to focus on an element that has been deleted, or is no longer the next or previous sibling of the selected element.</p><p>However, the ref which refers to the element in the component instance should not change, regardless of changes to the list. Therefore, if you access the nextElementSibling or previousElementSibling property directly on the ref at the time that your function executes, it should always return the correct element.</p><h3>Conclusion</h3><p>When building interactive user interfaces, it is important to always ask yourself <em>“what would the screen reader do?” . </em>This helps to ensure you develop the application so it can be used by all users, including those who rely on assistive technology, especially when it comes to focus management. In React, we can leverage the component lifecycle, refs, and the Node API to help us manage which node should be the document.activeElement.</p><p>I strongly recommend testing your application with a screen reader like VoiceOver, or even just navigating with a keyboard. As a sighted user fully capable of using a mouse, I often find keyboard navigation quicker and easier. An application that doesn’t cater for that just becomes frustrating.</p><p>Accessibility should not be an afterthought, or considered only needed by users with disability. Improving accessibility improves the user experience for everyone.</p><p>The full code repository for the examples shown in this article can be found at: <a href="https://github.com/laij84/mutable-list-focus">https://github.com/laij84/mutable-list-focus</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ddf4ed92186" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/improve-accessibility-in-your-react-app-by-managing-focus-in-mutable-content-4ddf4ed92186">Improve Accessibility in Your React App By Managing Focus in Mutable Content</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Frontend Applications By Mocking Your Entire API With Testing Tools]]></title>
            <link>https://medium.com/swlh/building-frontend-applications-by-mocking-your-entire-api-with-testing-tools-2f050359677f?source=rss-7a0f2b42dba5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f050359677f</guid>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[testing-tools]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Jason Lai]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 12:35:00 GMT</pubDate>
            <atom:updated>2021-02-23T21:32:28.119Z</atom:updated>
            <content:encoded><![CDATA[<h4>You don’t need a backend…(yet)</h4><h4>TypeScript, React, GraphQL and Apollo Client</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i3TGhQ41tD-nHDNk" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re a frontend developer, you’ve probably experienced being blocked while waiting on the backend API to be built. You could just hard code the templates and leave the integration until later, or import a JSON file of mock data to use, but neither of these solutions are particularly efficient as they don’t allow you to see the result of the actual code that will run in production.</p><p>Even if your backend API is ready and you have a local development environment to work with, configuring your application and populating your database can be a laborious process.</p><p>Luckily, <a href="https://www.apollographql.com/docs/react/">Apollo Client</a> ships with MockedProvider, a component that allows you to <a href="https://www.apollographql.com/docs/react/development-testing/testing/">test your React components</a> by mocking calls to your GraphQL endpoint. How does this help? The idea came to me one day while I was writing unit tests — if the MockedProvider could be used to hydrate my React App in the test environment JSDOM, then why not in the browser DOM?</p><p>This probably is not the intended use for MockedProvider, as the Apollo documentation only covers implementing it in the context of a test environment. However, I set out to put my theory to the test and found that this method works really well, improving my workflow and efficiency.</p><h4>Schema first design</h4><p>The first thing you must do is agree on a schema with the team who will be building the backend. This will save a lot of refactoring later on, and if all goes according to plan you will be able to swap out the MockedProvider for the real one and your application should work seamlessly.</p><p>Since Apollo Client uses GraphQL, you can start by writing the GraphQL types. In the example below, we’ll be using a simple Book and Author model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04a4ff0ef2c689dd818fb42e606bd8d3/href">https://medium.com/media/04a4ff0ef2c689dd818fb42e606bd8d3/href</a></iframe><p>You can optionally create a client side schema to pass to your instance of Apollo Client, if you want to be able to inspect your schema with the <a href="https://github.com/apollographql/apollo-client-devtools">Apollo Client Dev Tools</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4bc646f0e64fc51399d0698ea841614/href">https://medium.com/media/d4bc646f0e64fc51399d0698ea841614/href</a></iframe><h4>Generate TypeScript types</h4><p>This example is in TypeScript, so if you are using regular JS you can skip this step. <a href="https://graphql-code-generator.com/">GraphQL Code Generator</a> is an excellent tool to convert GraphQL types into TypeScript types. You can use their web tool or install their CLI tool. Here is the output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94f6a46b9d349a35dcc6e36f57003230/href">https://medium.com/media/94f6a46b9d349a35dcc6e36f57003230/href</a></iframe><h4>Write your GraphQL query</h4><p>Now that we know the structure of our data, we can write our query to fetch all our books.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/116736a69d966e90ebfbb677422ca968/href">https://medium.com/media/116736a69d966e90ebfbb677422ca968/href</a></iframe><p><strong>Note: </strong>If you are working with a REST API using apollo-link-rest you will need to include the @type directive in your queries to patch the __typename in your query results. For more info visit <a href="https://www.apollographql.com/docs/link/links/rest/#typename-patching">https://www.apollographql.com/docs/link/links/rest/#typename-patching</a></p><h4>Create your mocks</h4><p>Apollo’s MockedProvider expects a mocks prop, which is an array of MockedResponse&lt;T&gt;. You could hard code these, but it is much less brittle to use a mock generator. We’ll be using <a href="https://github.com/willryan/factory.ts">Factory.ts</a> with <a href="https://github.com/marak/Faker.js/">Faker</a>, but you can use any libraries that suit your needs. <a href="https://medium.com/@jaferson123">Jose Silva</a> has a good article explaining how to use <a href="https://medium.com/@jaferson123/tdd-factory-generator-with-factory-ts-and-faker-js-to-ease-your-testing-in-typescript-applications-5afdd45e6e8">Factory.ts and Faker with TDD</a>.</p><p>For each GraphQL type we will create a factory, which will generate instances of that type. We can also provide the corresponding TypeScript type to the factory to validate the shape of the mock data. Faker will also be used to generate realistic data for each property on our Book and Author.</p><p>Finally we can create our MockedResponse&lt;Query&gt; and leverage the buildList function on our factory to generate as many books as we want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddf5d91b0d6db52e6e87980ea10270c7/href">https://medium.com/media/ddf5d91b0d6db52e6e87980ea10270c7/href</a></iframe><h4>Prepare your Provider</h4><p>You’ll want an easy way to switch between the real ApolloProvider and the MockedProvider. There are many ways you can do this, for example you might conditionally render it depending on the node env (dev/production).</p><p>In this example, I’m just going to use a basic boolean useMocks prop to switch between the two.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20b00e69f7c406f0f84acecf673d31ad/href">https://medium.com/media/20b00e69f7c406f0f84acecf673d31ad/href</a></iframe><p>Now wrap the main contents of your App with the Provider component, so that it can access the GraphQL data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c927253dcbc401bda7b957deb01472f/href">https://medium.com/media/3c927253dcbc401bda7b957deb01472f/href</a></iframe><h4>Using the mock data in your component</h4><p>In our Books component we are going to use the useQuery hook to fetch the mock data from our MockedProvider.</p><pre>const { data, loading, error } = useQuery&lt;Query&gt;(GET_BOOKS)</pre><p>If you console.log(data) you should be able to see the generated mock data in the browser console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*CAeD28EeVCyeaZUnIqBhNA.png" /></figure><p>Now we can display this data in our component — the example below just renders it in a simple list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faec9fd83324a0c41b072507924bcffd/href">https://medium.com/media/faec9fd83324a0c41b072507924bcffd/href</a></iframe><p>You should be able to see your React app hydrated with mock data rendered in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDdaklCGkYYx4UYUDh6VYg.png" /></figure><p>This is a very basic example, but you can also do more complex mocks with MockedProvider, such as paginated queries or mutations, by creating a MockedResponse&lt;T&gt; for each query or mutation. For mutations, you can create a mock factory to generate the mutation payload.</p><p>This makes it much easier to build the frontend, especially interactive UI which would normally be dependent on an API response, such as CRUD operations.</p><p>You can read more about how to use MockedProvider at:</p><ul><li><a href="https://www.apollographql.com/docs/react/development-testing/testing/#mockedprovider">https://www.apollographql.com/docs/react/development-testing/testing/#mockedprovider</a></li><li><a href="https://www.apollographql.com/docs/react/development-testing/testing/#testing-mutation-components">https://www.apollographql.com/docs/react/development-testing/testing/#testing-mutation-components</a></li></ul><h4>Gotchas and common mistakes</h4><p>When working with MockedProvider I’ve come across a few idiosyncrasies that are good to be aware of to ensure it works properly.</p><ul><li>If your queries or mutations require variables, for example, a pagination limit and offset, the mock you pass to the MockedProvider must have the exact same variables defined that the useQuery hook will be called with in your component.</li><li>If your mock data objects <em>do not</em> have the __typename field, then you must <em>add</em> the prop addTypename={false} to your MockedProvider.</li><li>If your mock data objects <em>do</em> have the __typename field, you must <em>remove</em> the prop addTypename={false} (it is true by default).</li></ul><h4>Conclusion</h4><p>Using Apollo’s MockedProvider is an easy way to build frontend applications without relying on the backend API. There are a lot of benefits to this approach.</p><ul><li>The code you write is the code that will be used in production — your queries and mutations will work exactly the same with both the MockedProvider and the ApolloProvider. You don’t need to comment out chunks of code that handle your API requests and replace it with an imported JSON file to hydrate your UI.</li><li>You can easily test the performance of your application — using your mock factories you can generate hundreds of entries of data to see how your frontend app renders it.</li><li>You can easily do visual checks for edge cases by tweaking your mock factories. For example what if some of the books have extremely long titles?</li><li>You can reuse your mocks factories for unit/integration tests.</li><li>Development time is much quicker as you don’t have to wait on API changes to write and test your code, and view the results in the browser.</li></ul><p>Although this article focuses specifically on Apollo Client, this approach should work for any API client that provides tools for mocking requests, making development and testing faster and easier.</p><p>The full code repository for the examples shown in this article can be found at: <a href="https://github.com/laij84/apollo-mocked-provider">https://github.com/laij84/apollo-mocked-provider</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f050359677f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/building-frontend-applications-by-mocking-your-entire-api-with-testing-tools-2f050359677f">Building Frontend Applications By Mocking Your Entire API With Testing Tools</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>