<?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 David Cai on Medium]]></title>
        <description><![CDATA[Stories by David Cai on Medium]]></description>
        <link>https://medium.com/@davidwcai?source=rss-1c7538dd8dad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ajlX_WNZN_kifgh9.jpg</url>
            <title>Stories by David Cai on Medium</title>
            <link>https://medium.com/@davidwcai?source=rss-1c7538dd8dad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:49:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidwcai/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[Implement React Portals in Lit Web Components]]></title>
            <link>https://davidwcai.medium.com/implement-react-portals-in-lit-web-components-ed41257f4a67?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed41257f4a67</guid>
            <category><![CDATA[react-portal]]></category>
            <category><![CDATA[litelement]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 04:10:54 GMT</pubDate>
            <atom:updated>2022-06-02T04:10:54.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Portal" src="https://cdn-images-1.medium.com/max/1024/1*HKvw7jRzeh2V9p-QTWIq3g.jpeg" /></figure><p>React has a <a href="https://reactjs.org/docs/portals.html">createPortal</a> API to render a child node in a container node:</p><pre>ReactDOM.createPortal(child, container);</pre><p>The container node can be anywhere in the DOM. This enables interesting use cases such as injecting app-level overlays, e.g. Modal, Banner, and Toast to document.body :</p><pre>render() {<br>  return ReactDOM.createPortal(this.props.children, <strong>document.body</strong>);<br>}</pre><p>How can we create portals in Lit web components?</p><p>The solution is surprisingly easy — createRenderRoot :</p><pre>@customElement(&#39;banner&#39;)<br>export class Banner extends LitElement {<br>  render() {<br>    return html`<br>      &lt;div class=&quot;banner&quot;&gt;...&lt;/div&gt;<br>    `;<br>  }</pre><pre>  <strong>createRenderRoot</strong>() {<br>    return document.body;<br>  }<br>}</pre><p>By default, a Lit component renders its content inside its Shadow DOM. Something like this:</p><pre>&lt;banner&gt;<br>  |<br>  +- #shadow-root   &lt;------ render root<br>       |<br>       +- &lt;div class=&quot;banner&quot;&gt;</pre><p>The renderRoot points to the shadowRoot . We can customize the render root by implementing LitElement’s createRenderRoot method. Any HTMLElement can be returned from this method, e.g.:</p><pre>createRenderRoot() {<br>  return document.querySelector(&#39;#banner-container&#39;);<br>}</pre><p>The rendered content will now be injected to an HTML element with a “banner-container” ID:</p><pre>&lt;banner&gt;   &lt;------ An empty custom element without content</pre><pre>...</pre><pre>&lt;div id=&quot;overlay-container&quot;&gt;<br>  |<br>  +- &lt;div class=&quot;banner&quot;&gt;    &lt;---- Banner content is ported here</pre><p>The banner’s content is directly injected into the overlay container. There is no shadow DOM to encapsulate banner styles, which might be something you miss. To bring back shadow DOM for the rendered content, we can render a Lit component — banner-content, instead of a div in Banner’s render method:</p><pre>@customElement(&#39;banner&#39;)<br>export class Banner extends LitElement {<br>  render() {<br>    return html`<br>      <strong>&lt;banner-content&gt;...&lt;/banner-content&gt;</strong><br>    `;<br>  }</pre><pre>  createRenderRoot() {<br>    return document.querySelector(&#39;#overlay-container&#39;);<br>  }<br>}</pre><pre>@customElement(&#39;banner-content&#39;)<br>export class <strong>BannerContent</strong> extends LitElement {<br>  render() {<br>    return html`<br>      <strong>&lt;div class=&quot;banner&quot;&gt;...&lt;/div&gt;</strong><br>    `;<br>  }<br>}</pre><p>The banner-content is a Lit component which by default renders its content inside its own shadow DOM:</p><pre>&lt;banner&gt;   &lt;------ An empty custom element</pre><pre>...</pre><pre>&lt;div id=&quot;overlay-container&quot;&gt;<br>  |<br>  +- <strong>&lt;banner-content&gt;</strong>    &lt;---- Banner content is ported here<br>       |<br>       +- <strong>#shadow-root</strong>   &lt;---- Banner content&#39;s own shadow DOM<br>            |<br>            +- &lt;div class=&quot;banner&quot;&gt;</pre><p>Now, banner-content styles are encapsulated.</p><h3>Bonus</h3><p>Return this in the createRenderRoot method will make a Lit component to render its content in the Light DOM instead of Shadow DOM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed41257f4a67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mock GraphQL and REST in Storybook and Jest with MSW]]></title>
            <link>https://davidwcai.medium.com/mock-graphql-and-rest-in-storybook-and-jest-with-msw-78521ec44a9c?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/78521ec44a9c</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[storybook]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 22:01:47 GMT</pubDate>
            <atom:updated>2021-08-16T22:01:47.560Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is long (and dry), but at the end, you will have a setup that enables mocking GraphQL or REST responses at network level, and sharing the mocks between Storybook and Jest tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*haX0bUaS8rxYQsZU8fHCRg.jpeg" /></figure><p>Storybook is really good for developing components in isolation, especially for presentational (or “dumb”) components which are purely driven by their props (or their contexts). However, some “smart” components will need to fetch data via GraphQL or REST APIs. These components might also have UI treatment for loading and error states, depending on server responses.</p><p>To achieve the development-in-isolation goal, these server-side responses need to be mocked, ideally without any server.</p><p>One common approach is to use library-specific tools such as Apollo’s MockedProvider or Axio’s mock adapter to mock server response. These tools are often easy to setup and use. The downside, however, is that they are tied to specific data-fetching libraries. When you need to swap out these libraries, for example, migrating ApolloClient to React-Query, your mock tools will have to be changed too.</p><h3>MSW</h3><p>Mock Service Worker (<a href="https://mswjs.io/">MSW</a>) is a generic mocking tool that is not tied to any data-fetching library. Service Worker is an industry standard that is designed to intercept HTTP requests and override responses. With MSW, you can mock HTTP response in both browser (for Storybook) and Node (for Jest) environment.</p><p>Here is a screenshot showing how to mock responses for a GraphQL query (Persons) and mutation (UpdatePerson) in Storybook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5LRM3keCnOlCzFXhRYdtw.png" /><figcaption>MSW mocks for GraphQL queries and mutations in Storybook</figcaption></figure><p>In browser, HTTP requests will show up in the Network panel even when they are mocked, because requests are actually initiated but got intercepted and mocked by Service Worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yIZsSA9L5jvw_SvPbZAGw.png" /><figcaption>Mocked requests show up in browser’s dev tools</figcaption></figure><p>OK, but how do we integrate MSW with Storybook and Jest?</p><h3>Install</h3><p>First, install MSW:</p><pre>npm install msw --save-dev</pre><p>Then, generate a mock service worker script in a public directory. Run the following command at your project root:</p><pre>npx msw init &lt;PUBLIC_DIR&gt; --save</pre><p>&lt;PUBLIC_DIR&gt; is a directory that serves public static assets such as images. You can find the public directory for your project in this list: <a href="https://mswjs.io/docs/getting-started/integrate/browser#where-is-my-public-directory">https://mswjs.io/docs/getting-started/integrate/browser#where-is-my-public-directory</a>. If you don’t see a match in the list, don’t worry, just use public/for now. The generated script (mockServiceWorker.js) will be put in the “public” directory at project root.</p><p>The generated script should be committed to Git. Make sure you don’t git ignore this script. No need to change anything in the script.</p><p>After you run the above npx command, a new entry will be added to package.json:</p><pre>// package.json</pre><pre>&quot;msw&quot;: {<br>  &quot;workerDirectory&quot;: &quot;public&quot;<br>}</pre><p>This is for MSW to track the public directory in future.</p><h3>Integration with Storybook</h3><p>In the same package.json file where you defined the Storybook commands, add -s ./public to the commands, so Storybook will include the “public/mockServiceWorker.js” file when serving stories. For example:</p><pre>// package.json</pre><pre>&quot;scripts: {<br>  &quot;storybook&quot;: &quot;start-storybook <strong>-s ./public</strong>&quot;,<br>  &quot;build&quot;: &quot;build-storybook <strong>-s ./public</strong>&quot;<br>}</pre><p>Now, create a msw-utils.js file at your project root (the filename can be anything, but for this article, let’s just name it msw-utils.js):</p><pre>// msw-utils.js</pre><pre>import { setupWorker } from &quot;msw&quot;;<br>import { setupServer } from &quot;msw/node&quot;;</pre><pre>function setup() {<br>  let worker;<br>  let server;</pre><pre>  if (typeof global.process === &quot;undefined&quot;) {<br>    <em>// Setup mock service worker for browser environment<br>    </em>worker = setupWorker();<br>  } else {<br>    <em>// Setup mock service server for node environment<br>    </em>server = setupServer();<br>  }</pre><pre>  return { worker, server };<br>}</pre><pre><em>export</em> const { worker, server } = setup();<br><em>export</em> const mock = (worker || server).use;<br><em>export</em> { graphql, rest } from &quot;msw&quot;;</pre><p>Optionally, if you use <strong>TypeScript</strong>, create a msw-utils.ts instead like this:</p><pre>// msw-utils.ts</pre><pre>import { SetupWorkerApi, setupWorker } from &quot;msw&quot;;<br>import { SetupServerApi, setupServer } from &quot;msw/node&quot;;</pre><pre>function setup() {<br>  let worker: SetupWorkerApi | undefined;<br>  let server: SetupServerApi | undefined;</pre><pre>  if (typeof global.process === &quot;undefined&quot;) {<br>    <em>// Setup mock service worker for browser environment<br>    </em>worker = setupWorker();<br>  } else {<br>    <em>// Setup mock service server for node environment<br>    </em>server = setupServer();<br>  }</pre><pre>  return { worker, server };<br>}</pre><pre><em>export</em> const { worker, server } = setup();<br><em>export</em> const mock = (worker ?? server)!.use;<br><em>export</em> { graphql, rest } from &quot;msw&quot;;</pre><p>Note: there won’t be any server running even if setupServer indicates so.</p><p>In .storybook/preview.js (create if it doesn’t exist), we start the Mock Service Worker for Storybook:</p><pre>// .storybook/preview.js</pre><pre>import { worker } from &quot;../msw-utils&quot;;</pre><pre>const MSW_FILE = &quot;mockServiceWorker.js&quot;;</pre><pre><em>// In browser, start Mock Service Worker to mock HTTP responses<br></em><strong>worker.start</strong>({<br>  serviceWorker: { url: `./${MSW_FILE}` },</pre><pre>  <em>// Return the first registered service worker found with the name<br>  // of `mockServiceWorker`, disregarding all other parts of the URL<br>  </em>findWorker: scriptURL =&gt; scriptURL.includes(MSW_FILE),</pre><pre>  onUnhandledRequest: &quot;bypass&quot;<br>});</pre><p>Here, we import and start the worker with the following configurations:</p><ul><li><em>serviceWorker</em> — This is to tell MSW where to find the generated script “mockServiceWorker.js”.</li><li><em>findWorker</em> — This is to use the first found worker with the same file path.</li><li><em>onUnhandledRequest</em> — This configuration disables warnings in browser console for un-mocked requests.</li></ul><p>At this point, your project should have a file structure like this:</p><pre>your-project<br>  |<br>  + .storybook<br>  |  |<br>  |  + preview.js<br>  |<br>  + public<br>  |  |<br>  |  + mockServiceWorker.js // Generated script<br>  |<br>  + src<br>  |<br>  + msw-utils.js // or msw-utils.ts<br>  |<br>  + package.json</pre><p>With all these setup, it is time to write mocks in your Storybook stories.</p><h3>Mock data in Storybook</h3><p>In our Storybook file, we first import the <em>msw-utils</em> which we created in the above steps. (Your import path might be different.) Then, we define the mock data, and export a story using the ProfileCard component (not included in this article).</p><pre>// ProfileCard.stories.jsx</pre><pre>...<br>import { graphql, mock } from &quot;../../../msw-utils&quot;;</pre><pre>...</pre><pre>const PERSON_MOCK = {<br>  id: &quot;478620&quot;,<br>  name: { first: &quot;David&quot;, last: &quot;Cai&quot; },<br>  gender: &quot;male&quot;,<br>  age: 42<br>};</pre><pre>export const Profile = () =&gt; &lt;ProfileCard /&gt;;</pre><p>Now, here is the code to stub a response for a GraphQL query “Persons”:</p><pre>// ProfileCard.stories.jsx</pre><pre>...</pre><pre>export const Profile = () =&gt; &lt;ProfileCard /&gt;;<br>Profile.decorators = [<br>  story =&gt; {<br>    <strong>mock</strong>(<br>      <strong>graphql.query</strong>(<br>        &quot;Persons&quot;, <br>        (_req, res, ctx) =&gt; {<br>          return res(<strong>ctx.data</strong>({<br>            household: { persons: [PERSON_MOCK] } }));<br>        }<br>      )<br>    );<br>  <br>    return story();<br>  }<br>];</pre><p>ctx.data is used to return a mocked data as response. Persons is the query name we defined in the GraphQL document, for instance:</p><pre>// Query name in a graphql document</pre><pre>export const QUERY_PERSONS = gql`<br>  query <strong>Persons</strong> {<br>    household {<br>      persons {<br>        id<br>        name {<br>          first<br>          last<br>        }<br>        gender<br>        age<br>      }<br>    }<br>  }<br>`;</pre><p>For mocking mutations,</p><pre>// ProfileCard.stories.jsx</pre><pre>...</pre><pre>Profile.decorators = [<br>  story =&gt; {<br>    mock(<br>      graphql.query(&quot;Persons&quot;, ...),</pre><pre>      <strong>graphql.mutation</strong>(<br>        &quot;UpdatePerson&quot;,<br>        (req, res, ctx) =&gt; {<br>          const { updatedPerson } = <strong>req.variables</strong>;<br>          return res(ctx.data({<br>            household: { persons: [updatedPerson] }<br>          }));<br>        }<br>      )<br>    );<br>  <br>    return story();<br>  }<br>];</pre><p>To mock REST data, use rest instead of graphql, for example:</p><pre>mock(<br>  <strong>rest.get</strong>(&quot;/persons/:personId&quot;, (req, res, ctx) =&gt; {<br>    const { personId } = req.params;</pre><pre>    return res(ctx.json({ id: personId, firstName: &quot;David&quot; }));<br>  })<br>)</pre><h3>Mock loading state</h3><p>The ctx.delay function can be used to mimic network latency.</p><pre>res(<br>  <strong>ctx.delay(2000)</strong>, // Delay response for 2 seconds<br>  ctx.data({ your: data })<br>);</pre><p>To keep staying in the loading state, you can replace the arbitrary milliseconds with “infinite”:</p><pre>ctx.delay(<strong>&quot;infinite&quot;</strong>);</pre><p>To mimic random latency, you can omit the argument:</p><pre><strong>ctx.delay()</strong>; // Random server response time</pre><h3>Mock error state</h3><p>Use ctx.errors function to mock server-side errors (either GraphQL or REST errors):</p><pre>res(<br>  <strong>ctx.errors</strong>([<br>    { message: &quot;Failed to find person&quot; }<br>  ])<br>);</pre><p>To mock network errors, use ctx.status:</p><pre>res(<strong>ctx.status</strong>(404, &quot;Resource not found&quot;));</pre><p>More utility functions can be found at <a href="https://mswjs.io/docs/api">https://mswjs.io/docs/api</a>.</p><h3>Integration with Jest</h3><p>Component stories defined in Storybook are often shared with their unit tests, including the mocks. In order to share MSW mocks, we will need two things — the “@storybook/testing-react” plugin, and a Jest setup file.</p><p>The @storybook/testing-react plugin includes the Storybook decorators we created for each story. Since we define mocks using decorators, this plugin will automatically tie stories with their mocks. Run the following command to install it:</p><pre>npm install @storybook/testing-react --save-dev</pre><p>Once, this plugin is installed, we can import and compose stories with the composeStories utility:</p><pre>// ProfileCard.test.jsx</pre><pre>import { <strong>composeStories</strong> } from &quot;@storybook/testing-react&quot;;<br>import * as stories from &quot;./ProfileCard.stories&quot;;</pre><pre>const { Self } = <strong>composeStories(stories)</strong>;</pre><pre>describe(&quot;ProfileCard&quot;, () =&gt;  {<br>  it(&quot;should render a profile card&quot;, () =&gt; {<br>    render(&lt;Self /&gt;);<br>    // ...<br>  });<br>});</pre><p>Before we run the test, we also need to setup Jest to start the Mock Service Worker, reset all mocks after each test, and close the worker once all tests are completed. To do that, we will need a Jest setup file like this:</p><pre><em>// jest.setup.js</em></pre><pre>import { server } from &quot;./msw-utils&quot;;</pre><pre><em>// Setup Mock Service Server for unit test<br></em><strong>beforeAll(() =&gt; server.listen());<br>afterEach(() =&gt; server.resetHandlers());<br>afterAll(() =&gt; server.close());</strong></pre><p>In project’s package.json, we register the setup file with Jest config:</p><pre>// package.json</pre><pre>&quot;jest&quot;: {<br>  <em>// ...<br>  </em>&quot;<strong>setupFilesAfterEnv</strong>&quot;: [&quot;&lt;rootDir&gt;/<strong>jest.setup.js</strong>&quot;]<br>}</pre><h3>Recap</h3><p>Although it takes a few steps to set things up, most of these steps are one-time only.</p><ul><li>Install msw and @storybook/testing-react (<strong>One-time setup</strong>)</li><li>Generate mockServiceWorker.js in a public directory (<strong>One-time setup</strong>)</li><li>Change storybook commands to include the generated mockServiceWorker.js (<strong>One-time setup</strong>)</li><li>Create msw-utils (<strong>One-time setup</strong>)</li><li>Start MSW in .storybook/preview.js (<strong>One-time setup</strong>)</li><li>Start MSW in Jest setup file (<strong>One-time setup</strong>)</li><li>Mock data in Storybook</li></ul><p>Your project might have the following structure:</p><pre>your-project<br>  |<br>  + .storybook<br>  |  |<br>  |  + preview.js              // Storybook preview setup<br>  |<br>  + public<br>  |  |<br>  |  + mockServiceWorker.js    // Generated script<br>  |<br>  + src<br>  |  |<br>  |  + ProfileCard.jsx         // Component<br>  |  |<br>  |  + ProfileCard.stories.jsx // Storybook stories<br>  |  |<br>  |  + ProfileCard.test.jsx.   // Jest test<br>  |<br>  + jest.setup.js              // Jest setup<br>  |<br>  + msw-utils.js               // MSW utils<br>  |<br>  + package.json</pre><p>With this setup, we can mock HTTP responses at network level, without relying on any specific data-fetching library. We can also share MSW mocks between Storybook and Jest tests to maximize code re-usability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78521ec44a9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fix Cypress “Invalid or unexpected token” errors in parallel runs]]></title>
            <link>https://davidwcai.medium.com/fix-cypress-invalid-or-unexpected-token-errors-in-parallel-runs-e887d7efa945?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/e887d7efa945</guid>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[browser-testing]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[cypress]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 19:59:21 GMT</pubDate>
            <atom:updated>2021-03-17T17:28:43.846Z</atom:updated>
            <content:encoded><![CDATA[<p>Cypress test has been working very well for my project. But lately I started to get the mysterious “Invalid or unexpected token” errors after I changed my CI pipeline to use Cypress’ parallel testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HiY8x3JEHhNEUmll" /><figcaption>Photo by <a href="https://unsplash.com/@dnevozhai?utm_source=medium&amp;utm_medium=referral">Denys Nevozhai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The error message “<em>originated from your test code</em>” made me think if there is any syntax error in my test specs. But if so, the Cypress test should have failed every time, rather than intermittently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTpyci6Dxa2CfUCGXru_fw.png" /><figcaption>Invalid or unexpected token error</figcaption></figure><p>My Cypress test specs are coded in TypeScript. This led me to speculate if compiling TypeScript code in Cypress’ parallel mode could cause overwriting in files among Cypress testers. A bit of google search also confirmed my theory.</p><p>One solution that worked for me is to isolate test files in their test runs, so test code will not get overwritten by other testers.</p><p>In plugins/index.js, I have this code to append unique IDs to filenames before Webpack processes test files:</p><pre>// plugins/index.js</pre><pre>const webpackPreprocessor = require(&quot;@cypress/webpack-batteries-included-preprocessor&quot;);</pre><pre>const { v4: uuid } = require(&quot;uuid&quot;);</pre><pre>const filePreprocessor = webpackPreprocessor({ typescript: &quot;typescript&quot; });</pre><pre>module.exports = on =&gt; {</pre><pre>  const id = uuid();</pre><pre>  on(&quot;file:preprocessor&quot;, file =&gt; {</pre><pre>    file.outputPath = file.outputPath.replace(/^(.*\/)(.*?)(\..*)$/, `$1$2.${id}$3`);</pre><pre>    return filePreprocessor(file);</pre><pre>  });</pre><pre>};</pre><p>This is the key line:</p><pre>file.outputPath.replace(/^(.*\/)(.*?)(\..*)$/, `$1$2.${id}$3`)</pre><p>If a file’s path is “cypress/integration/abc.spec.ts”, the path will be replaced with “cypress/integration/abc.&lt;uuid&gt;.spec.ts”. &lt;uuid&gt; is unique among each tester run.</p><p>I need to install “@cypress/webpack-batteries-included-preprocessor” and “@cypress/webpack-preprocessor”, so my plugin file can access webpack and its file preprocessors.</p><pre>npm install -D @cypress/webpack-preprocessor @cypress/webpack-batteries-included-preprocessor</pre><p>With this fix, I haven’t encountered any “Invalid or unexpected token” error. Hope this tip helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e887d7efa945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch delete git tags by dates]]></title>
            <link>https://davidwcai.medium.com/batch-delete-git-tags-by-dates-6f79a4705ea6?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f79a4705ea6</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Thu, 28 May 2020 23:54:15 GMT</pubDate>
            <atom:updated>2020-05-28T23:54:15.647Z</atom:updated>
            <content:encoded><![CDATA[<p>TLDR;</p><pre>git for-each-ref --format &#39;%(creatordate:iso) %(refname)&#39; refs/tags | grep &#39;2020-05-28 12:53&#39; | sed -nE &#39;s/.+refs\//:refs\//p&#39; | xargs git push origin</pre><pre>git fetch --prune origin +refs/tags/*:refs/tags/*</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoCgdIorZH_cphMvS-S8RA.jpeg" /><figcaption>Tags</figcaption></figure><p>The other day, I accidentally created 60 git tags, and pushed all of them to the master branch. Oops!</p><p>Now I have a choice — delete them one by one, or delete them in a batch?</p><p>If the tags that I need to delete aren’t that many, I will just do:</p><pre>git tags -d cat<br>git push origin :refs/tags/cat</pre><p>The first command deletes tag “cat” in my local, and the second command deletes it in the remote.</p><p>But … I don’t want to repeat myself for 60 times...</p><p>So I came up with this:</p><pre>git for-each-ref --format &#39;%(creatordate:iso) %(refname)&#39; refs/tags | grep &#39;2020-05-28 12:53&#39;</pre><p>This command lists all tags created at 12:53 on May 28, 2020 — the time when I accidentally created “cat”, “dog”, “rat”, and other 57 tags related to small animals. The output looks like this:</p><pre>2020-05-28 12:53:04 -0700 refs/tags/cat<br>2020-05-28 12:53:04 -0700 refs/tags/dog<br>2020-05-28 12:53:24 -0700 refs/tags/rat</pre><p>“-0700” indicates my timezone.</p><p>The reason why I included date and time in the output is to double check the tags to make sure they are the ones I want to delete. Don’t want one mistake to lead to another, eh?</p><p>Then, I pipe this output to the powerful “sed” to remove date, time, and time zone, and replace “refs/” with “:refs/” which I will use later.</p><pre>git for-each-ref --format &#39;%(creatordate:iso) %(refname)&#39; refs/tags | grep &#39;2020-05-28 12:53&#39; | sed -nE &#39;s/.+refs\//:refs\//p&#39;</pre><p>The output looks like this:</p><pre>:refs/tags/cat<br>:refs/tags/dog<br>:refs/tags/rat</pre><p>Finally, I pipe the output as arguments to the “git push origin” command:</p><pre>git for-each-ref --format &#39;%(creatordate:iso) %(refname)&#39; refs/tags | grep &#39;2020-05-28 12:53&#39; | sed -nE &#39;s/.+refs\//:refs\//p&#39; | xargs git push origin</pre><p>This is equivalent to:</p><pre>git push origin :refs/tags/cat :refs/tags/dog :refs/tags/rat</pre><p>Of course, in my case, I have 60 tags to type. And that’s why I’d like to automatically generate all the tag names using the “git for-each-ref” command.</p><p>I also need to clean up the tags deleted in the remote but left in my local.</p><pre>git fetch --prune origin +refs/tags/*:refs/tags/*</pre><p>This command removes all tags present in my local but not in the remote.</p><p>To recap, these two commands are:</p><pre>git for-each-ref --format &#39;%(creatordate:iso) %(refname)&#39; refs/tags | grep &#39;2020-05-28 12:53&#39; | sed -nE &#39;s/.+refs\//:refs\//p&#39; | xargs git push origin</pre><pre>git fetch --prune origin +refs/tags/*:refs/tags/*</pre><p>Of course, replace the date time with yours.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f79a4705ea6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Testing Library and the “not wrapped in act” Errors]]></title>
            <link>https://davidwcai.medium.com/react-testing-library-and-the-not-wrapped-in-act-errors-491a5629193b?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/491a5629193b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 02:21:29 GMT</pubDate>
            <atom:updated>2020-10-15T18:39:05.864Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently upgraded React and <a href="https://github.com/testing-library/react-testing-library">React testing library</a>. Very happy about the upgrade. But I start to see test errors like this:</p><pre>When testing, code that causes React state updates should be wrapped into act(...):<br>     <br>     act(() =&gt; {<br>       /* fire events that update state */<br>     });<br>     /* assert on the output */<br>     <br>This ensures that you&#39;re testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act</pre><p>Why? And how do I fix this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t52l4ODQxskVmEj4qZ3F3g.jpeg" /></figure><h4>Why do I get this error?</h4><p>In test, the code to render and update React components need to be included in React’s call stack. So the test behaves more similar to the user experience in real browsers.</p><p>Here is a simplified example from React’s document:</p><pre>// With react-dom/test-utils</pre><pre>it(&quot;should render and update a counter&quot;, () =&gt; {<br>  // Render a component<br>  <strong>act(() =&gt; {</strong><br>    ReactDOM.<strong>render</strong>(&lt;Counter /&gt;, container);<br>  });<br>  ...  <br><br>  // Fire event to trigger component update<br>  <strong>act(() =&gt;</strong> <br>    button.<strong>dispatchEvent</strong>(new MouseEvent(&#39;click&#39;, {bubbles: true})); <br>  });<br>  ...<br>});</pre><p>React testing library already integrated act with its APIs. So in most cases, we do not need to wrap render and fireEvent in act. For example:</p><pre>// With react-testing-library</pre><pre>it(&quot;should render and update a counter&quot;, () =&gt; {<br>  // Render a component<br>  const { getByText } = <strong>render</strong>(&lt;Counter /&gt;;<br>  ...  <br><br>  // Fire event to trigger component update<br>  <strong>fireEvent.click</strong>(getByText(&quot;Save&quot;));<br>  ...<br>});</pre><p>However, if your test still complains about “not wrapped in act(…)”, you might encounter one of these 4 cases described below.</p><h4>Case 1: Asynchronous Updates</h4><p>Test code somehow triggered a testing component to update in an asynchronous way. Here is an example:</p><pre>const MyComponent = () =&gt; {<br>  const [person, setPerson] = React.useState();</pre><pre>  const handleFetch = React.useCallback(async () =&gt; {<br>    const { data } = <strong><em>await</em> fetchData()</strong>;<br>    setPerson(data.person); <strong><em>// &lt;- Asynchronous update</em></strong><em><br>  </em>}, []);</pre><pre><em>  return</em> (<br>    &lt;button <em>type</em>=&quot;button&quot; <em>onClick</em>=&quot;handleFetch&quot;&gt;<br>      {person ? person.name : &quot;Fetch&quot;}<br>    &lt;/button&gt;<br>  );<br>};</pre><p>The following test will have the “not wrapped in act” error:</p><pre>it(&quot;should fetch person name&quot;, () =&gt; {<br>  const { getByText } = render(&lt;MyComponent /&gt;);<br>  fireEvent.click(getByText(&quot;Fetch&quot;));</pre><pre>  expect(getByText(&quot;David&quot;)).toBeInTheDocument();<br>});</pre><p>fireEvent.click triggers fetchData to be called, which is an asynchronous call. When its response comes back, setPerson will be invoked, but at this moment, the update will happen outside of React’s call stack.</p><p><strong>Solution</strong></p><p>Before assertions, wait for component update to fully complete by using waitFor. waitFor is an API provided by React testing library to wait for the wrapped assertions to pass within a certain timeout window.</p><pre>it(&quot;should fetch person name&quot;, <strong>async</strong> () =&gt; {<br>  const { getByText } = render(&lt;MyComponent /&gt;);<br>  fireEvent.click(getByText(&quot;Fetch&quot;));</pre><pre>  <strong>await waitFor</strong>(() =&gt; {<br>    expect(getByText(&quot;David&quot;)).toBeInTheDocument();<br>  });<br>});</pre><h4>Case 2: Jest Fake Timers</h4><p>When you have setTimeout or setInterval in your component:</p><pre>const Toast = () =&gt; {<br>  const [isVisible, setIsVisible] = React.useState(true);<br>  React.useEffect(() =&gt; {<br>    <strong>setTimeout</strong>(() =&gt; { setIsVisible(false);}, 1000);<br>  }, []);</pre><pre><em>  return</em> isVisible ? &lt;div&gt;Toast!&lt;/div&gt; : null;<br>};</pre><p>… and use Jest’s fake timers to manipulate time:</p><pre>it(&quot;should display Toast in 1 sec&quot;, () =&gt; {<br>  <strong>jest.useFakeTimers()</strong>;<br>  const { queryByText } = render(&lt;MyComponent /&gt;);<br>  <strong>jest.advanceTimersByTime(1000)</strong>;</pre><pre>  expect(queryByText(&quot;Toast!&quot;)).not.toBeInTheDocument();<br>});2</pre><p>…, unit test has no idea that advancing timers will cause component updates, and you will get the “not wrapped in act” error.</p><p><strong>Solution</strong></p><p>Wrap Jest’s timer manipulations in an act block, so test will know that advancing time will cause component to update:</p><pre>it(&quot;should display Toast in 1 sec&quot;, () =&gt; {<br>  jest.useFakeTimers();<br>  const { queryByText } = render(&lt;MyComponent /&gt;);<br>  <strong>act(() =&gt; {</strong><br>    jest.advanceTimersByTime(1000);<br>  <strong>});</strong></pre><pre>  expect(queryByText(&quot;Toast!&quot;)).not.toBeInTheDocument();<br>});</pre><h4>Case 3: Premature Exit</h4><p>Your test prematurely exits before components finish rendering or updating.</p><p>This normally happens in components that have loading state, e.g. components fetching data using GraphQL or REST.</p><pre>const MyComponent = () =&gt; {<br>  const { <strong>loading</strong>, data } = useQuery(QUERY_ACCOUNTS);</pre><pre>  r<em>eturn</em> <strong>loading</strong> ? (<br>    &lt;div&gt;Loading ...&lt;/div&gt;<br>  ) : (<br>    &lt;div&gt;{data.accounts.length}&lt;/div&gt;<br>  );<br>};</pre><p>The test checks if “Loading …” is present.</p><pre>it(&quot;should display loading state&quot;, () =&gt; {<br>  const { getByText } = render(<br>    &lt;MockedApolloProvider <em>mocks</em>={accountMock}&gt;<br>      &lt;MyComponent /&gt;<br>    &lt;/MockedApolloProvider&gt;<br>  );</pre><pre>  expect(getByText(&quot;Loading ...&quot;)).toBeInTheDocument();<br>});</pre><p>However, the `it` block exits before the loading state disappears and data comes back. This kind of test will also cause “not wrapped in act” errors.</p><p><strong>Solution</strong></p><p>Make sure the test exits after all the rendering and updates are done. To do that, we can wait for the loading state to disappear:</p><pre>it(&quot;should display loading state&quot;, <strong>async</strong> () =&gt; {<br>  const { getByText, queryByText } = render(<br>    &lt;MockedApolloProvider mocks={accountMock}&gt;<br>      &lt;MyComponent /&gt;<br>    &lt;/MockedApolloProvider&gt;<br>  );</pre><pre>  expect(getByText(&quot;Loading ...&quot;)).toBeInTheDocument();<br>  <strong>await waitFor(() =&gt; {<br>    expect(queryByText(&quot;Loading ...&quot;)).not.toBeInTheDocument();<br>  });</strong><br>});</pre><p>Alternatively, you can use waitForElementToBeRemoved which is a wrapper around waitFor.</p><pre>await <strong>waitForElementToBeRemoved</strong>(() =&gt; queryByText(&quot;Loading ...&quot;));</pre><h4>Case 4: Formik Updates</h4><p>This is actually another variation of Case 1. It goes like this: test simulates events to change values in form inputs, e.g. changing value in a text input. If the form input is managed by Formik, your test will have a chance to run into “not wrapped in act” errors.</p><pre>it(&quot;should validate phone numbers&quot;, () =&gt; {<br>  ...</pre><pre>  <strong>fireEvent.change</strong>(getByPlaceholder(&quot;Phone&quot;), {<br>    target: { value: &quot;123456789&quot; }<br>  });<br>  fireEvent.click(getByText(&quot;Save&quot;));</pre><pre>  expect(getByText(<br>    &quot;Please enter a valid phone number&quot;<br>  )).toBeInTheDocument();<br>});</pre><p><strong>Solution</strong></p><p>Similar to Case 1, wait for all updates to complete, then perform assertions:</p><pre>it(&quot;should validate phone numbers&quot;, async () =&gt; {<br>  ...</pre><pre>  fireEvent.change(getByPlaceholder(&quot;Phone&quot;), {<br>   target: { value: &quot;123456789&quot; }<br>  });<br>  fireEvent.click(getByText(&quot;Save&quot;));</pre><pre>  <strong>await waitFor(() =&gt; {</strong><br>    expect(getByText(<br>      &quot;Please enter a valid phone number&quot;<br>    )).toBeInTheDocument();<br>  <strong>})</strong>;<br>});</pre><h4>Conclusion</h4><p>In test, React needs extra hint to understand that certain code will cause component updates. To achieve that, React-dom introduced act API to wrap code that renders or updates components. React testing library already wraps some of its APIs in the act function. But in some cases, you would still need to use waitFor, waitForElementToBeRemoved, or act to provide such “hint” to test.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=491a5629193b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript 3.7 features you absolutely should use]]></title>
            <link>https://davidwcai.medium.com/typescript-3-7-features-you-absolutely-should-use-25f9d9577816?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/25f9d9577816</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Wed, 15 Jan 2020 20:46:03 GMT</pubDate>
            <atom:updated>2020-01-16T17:09:21.194Z</atom:updated>
            <content:encoded><![CDATA[<p>If I have to choose the most useful features new to TypeScript 3.7, these two are on the very top of the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RA6ZuuPnRaSGk4adGoXenQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hannes_wolf?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hannes Wolf</a> on <a href="https://unsplash.com/s/photos/script?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Optional Chaining</h3><p>All of us JavaScript developers at some points of our career will unfortunately encounter this infamous error:</p><blockquote>“Uncaught TypeError: Cannot read property … of undefined”</blockquote><p>This is the equivalent to the “billion dollar mistake” — NPE (Null Pointer Exceptions) in the JavaScript land. And it is really easy to run into this kind of bugs.</p><pre>const data = fetchAccountPerformance();<br>doSomethingWith(<strong>data.accounts.performance</strong>);</pre><p>…but “<em>data.accounts</em>” can be “<em>undefined</em>”. And accessing “<em>performance</em>” from “<em>data.accounts</em>” will likely cause the above error.</p><p>To avoid this error, we might have to write some guarding code like this:</p><pre>if (<br>  <strong>data &amp;&amp; <br>  data.accounts &amp;&amp; <br>  data.accounts.performance</strong>)<br>{<br>  doSomethingWith(data.accounts.performance);<br>}</pre><p>Yes, very wordy.</p><p>Now with <strong>TypeScript 3.7</strong>, you can do this:</p><pre>if (<strong>data?.accounts?.performance</strong>) {<br>  doSomethingWith(data.accounts.performance);<br>}</pre><p>Much more concise.</p><p>“<em>a?.b</em>” is equivalent to:</p><pre>(a === <strong>null</strong> || a === <strong>undefined</strong>) ?<br>  undefined : <br>  a.b;</pre><p>So “<em>data?.accounts?.performance”</em> is equivalent to:</p><pre>(data === null || data === undefined) ?<br>  undefined :<br>  (data.accounts === null || data.accounts === undefined) ? <br>    undefined : <br>    data.accounts.performance;</pre><p>However, be aware that “<em>a &amp;&amp; b</em>” and “<em>a?.b</em>” are not necessarily 1-to-1 exchangeable. Here is an example:</p><pre>const a = &quot;&quot;;<br>console.log(a &amp;&amp; a.length); // <strong>&quot;&quot;<br></strong>console.log(a?.length); // <strong>0</strong></pre><p>In the case of “<em>a &amp;&amp; a.length</em>”, <em>a.length</em> will not be evaluated because “<em>a</em>” is an empty string, thus, falsy. The “<em>&amp;&amp;</em>” operator then skipped whatever on its right side, and returned the falsy value — an empty string.</p><p>However, in the case of “<em>a?.length</em>”, “<em>a</em>” is falsy but not <em>null</em> nor <em>undefined</em>. So “<em>.length</em>” will still be evaluated, and return <em>0</em>.</p><h3>Nullish Coalescing</h3><p>We often need to provide a default value if a value is unavailable.</p><pre>const name = person.name || &quot;David&quot;;</pre><p>If <em>person.name</em> is falsy (e.g., <em>null</em>, <em>undefined</em>, or <em>“”</em>), “David” will be assigned to variable <em>name</em> instead.</p><p>This all works well, but in some situations things can get tricky:</p><pre>const amount = position.numberOfShares || 100;</pre><p>The intention is to assign 100 to variable <em>amount</em> if <em>position.numberOfShares</em> is unavailable. But what if the <em>numberOfShares</em> is really 0?</p><p>0 is falsy, the “<em>||</em>” operator will then evaluate the right side, and return 100. Even if 0 is a legit value, it will still be overridden by 100. This is not what we wanted.</p><p>With <strong>TypeScript 3.7</strong>, you can now do this:</p><pre>const amount = position.numberOfShares <strong>?? 100</strong>;</pre><p>100 will be used only when <em>numberOfShares</em> is <em>null</em> or <em>undefined</em>. The above code is equivalent to:</p><pre>const amount = <br>  (position.numberOfShares === null ||<br>  position.numberOfShares === undefined) ?<br>    100 :<br>    position.numberOfShares;</pre><h3>Conclusion</h3><p>Optional Chaining and Nullish Coalescing are two features introduced by TypeScript 3.7. I found them very useful. For a full list of v3.7 features, see <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html">this</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25f9d9577816" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management in React with Reducer but not Redux]]></title>
            <link>https://davidwcai.medium.com/state-management-in-react-with-reducer-but-not-redux-3e76824fe4e5?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e76824fe4e5</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reducer]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Tue, 31 Dec 2019 22:53:39 GMT</pubDate>
            <atom:updated>2020-01-16T17:10:14.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TJ4xOkqwu8ih_KFgSUtFA.jpeg" /></figure><p>I truly believe that if React’s Context and Hook APIs came out before Redux’s inception, the adoption rate of Redux will be much lower compared to what it is now. Redux is likely overused in many projects where state management can be simply done using React’s built-in Context and Hook APIs instead. <a href="https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367">You might not need Redux</a> after all.</p><p>Before the introduction of Context, in a deeply nested component tree, to propagate changes from the top of a component tree down to a leaf node, developers have to pass state through multiple levels of components, e.g. grandparent to parent, to child, or even grand child. Developers will have to introduce a bunch of props just to pass the state down. This problem is commonly known as “prop drilling”.</p><p>And when a descendent component needs to communicate changes back to its ancestral component, changes will have to be bubbled up via callback props along the component tree branch from bottom to top. This is the inverted “prop drilling”.</p><p>Redux can be used to solve these issues by having a global state store accessible at any level of a component tree.</p><p>How do we create such state store without Redux?</p><p>(This post is inspired by Kent C. Dodds’ <a href="https://kentcdodds.com/blog/how-to-use-react-context-effectively">article</a>.)</p><h3>App</h3><p>We’d like to declare a state store close to the top level of our component tree. Something like this:</p><pre>// App.js</pre><pre>import { AppStore } from &quot;./store&quot;;</pre><pre>const defaultState = { name: &quot;Jane&quot; };</pre><pre>export function App() {<br>  return (<br>    <strong>&lt;AppStore defaultState={defaultState}&gt;</strong><br>      &lt;Greeter /&gt;<br>    <strong>&lt;/AppStore&gt;</strong><br>  );<br>}</pre><p>AppStore’s child — Greeter and its descendants will now have access to AppStore’s state and its dispatch function. We will go through AppStore in the following sections.</p><h3>Access store state and dispatch</h3><p>In our simple example, the Store’s child component — Greeter reads the “name” from the store state, and calls the “dispatch” function to change the name:</p><pre>// Greeter.js</pre><pre>import { useAppState, useAppDispatch } from &quot;./store&quot;;</pre><pre>export function Greeter() {<br>  <strong>const { name } = useAppState();</strong><br>  <strong>const dispatch = useAppDispatch();</strong></pre><pre>  const handleClick = () =&gt; {<br>    dispatch({ type: &quot;UPDATE_NAME&quot;, name: &quot;Joe&quot; });<br>  };</pre><pre>  return (<br>    &lt;button type=&quot;button&quot; onClick={handleClick}&gt;<br>      Hello, {name}!<br>    &lt;/button&gt;<br>  );<br>}</pre><p>The “useAppState” and “useAppDispatch” are two custom React hooks. The former is to read state from the store, the latter is to change state in the store. We will talk about them in a minute. But first, we will dive to the utility that creates Store components.</p><h3>Store utility</h3><p>The “createStore” function is a factory that produces a state store.</p><pre>// util.js</pre><pre>export function <strong>createStore(reducer)</strong> {<br><strong>  const StateContext = React.createContext();<br>  const DispatchContext = React.createContext();</strong></pre><pre>  function <strong>Store</strong>({ defaultState = {}, children }) {<br>    const [state, dispatch] = React.useReducer(<br>      reducer,<br>      defaultState<br>    );</pre><pre>    return (<br>      <strong>&lt;StateContext.Provider value={state}&gt;<br>        &lt;DispatchContext.Provider value={dispatch}&gt;</strong><br>          {children}<br>        <strong>&lt;/DispatchContext.Provider&gt;<br>      &lt;/StateContext.Provider&gt;</strong><br>    );<br>  }</pre><pre>  return Store;<br>}</pre><p>This function creates two React contexts — one for the store state(StateContext), and one for the dispatch function (DispatchContext). The function returns a Store component which wraps these two contexts and supplies values from these contexts.</p><p>The createStore function takes a reducer as its argument. The “reducer” is just your plain old reducer function.</p><h3>Reducer</h3><pre>// reducer.js</pre><pre>export function reducer(state, action) {<br>  switch (action.type) {<br>    case &quot;UPDATE_NAME&quot;:<br>      return { ...state, name: action.name };<br>    default:<br>      throw new Error(`Unsupported action: ${action.type}`);<br>  }<br>}</pre><p>Nothing special here. This is just a standard reducer function.</p><h3>useStoreState and useStoreDispatch</h3><p>Now we have a “createStore” function that takes a reducer and returns a Store component, but how can descendant components access the state and dispatch from the store? In order to do that, we need to enhance this “createStore” utility to return two additional custom hooks — “useStoreState” and “useStoreDispatch”:</p><pre>// util.js</pre><pre>export function createStore(reducer) {<br><strong>  </strong>const StateContext = React.createContext();<br>  const DispatchContext = React.createContext();</pre><pre>  function Store({ defaultState = {}, children }) {<br>    const [state, dispatch] = React.useReducer(<br>      reducer,<br>      defaultState<br>    );</pre><pre>    return (<br>      &lt;StateContext.Provider value={state}&gt;<br>        &lt;DispatchContext.Provider value={dispatch}&gt;<br>          {children}<br>        &lt;/DispatchContext.Provider&gt;<br>      &lt;/StateContext.Provider&gt;<br>    );<br>  }</pre><pre>  function <strong>useStoreState</strong>() {<br>    const context = React.useContext(StateContext);<br>    if (!context) {<br>      throw new Error(<br>        &quot;useStoreState must be used within a Provider&quot;<br>      );<br>    }</pre><pre>    return context;<br>  }</pre><pre>  function <strong>useStoreDispatch</strong>() {<br>    const context = React.useContext(DispatchContext);<br>    if (!context) {<br>      throw new Error(<br>        &quot;useStoreDispatch must be used within a Provider&quot;<br>      );<br>    }</pre><pre>    return context;<br>  }</pre><pre>  return <strong>[Store, useStoreState, useStoreDispatch]</strong>;<br>}</pre><p>These two custom hooks simply call React.useContext to read the values from the contexts. The “useStoreState” hook returns the store state, and the “useStoreDispatch” hook returns the dispatch function. They also added checks to ensure they can only be used inside their individual context providers.</p><p>Notice that we included these two custom hooks in the returned array together with the Store component.</p><p>Now let’s see how we use this function to create a state store.</p><h3>State store</h3><p>The “createStore” function shown above is generic and reusable. In our example, we use it to create an AppStore component, and two custom hooks — useAppState and useAppDispatch:</p><pre>// store.js</pre><pre>import { createStore } from &#39;./util&#39;;<br>import { reducer } from &quot;./reducer&quot;;</pre><pre>const <strong>[<br>  AppStore,<br>  useAppState,<br>  useAppDispatch<br>]</strong> = <strong>createStore</strong>(reducer);</pre><pre>export { AppStore, useAppState, useAppDispatch };</pre><p>Now we have a store, and two hooks to access it.</p><p>Unlike Redux, you are encouraged to create multiple stores, for example, we can use createStore to create a SessionStore for managing user sessions, or a WorkingCopyStore for caching user’s input in a rich text editor, etc. And these stores don’t have to be always at the top level of a component tree. They are usually used to wrap complicate components, and provide state management for those components.</p><h3>Debuggability</h3><p>Is it even a word?</p><p>One benefit of using Redux is the awesome developer tool that tracks state changes, and presents them in a nice way right in your browser. This made debugging Redux apps very easy. With our createStore function, we might be able to provide similar debuggability by adding just a little bit code to the createStore function:</p><h3>Track actions</h3><p>To report actions in their dispatched sequence, we can “proxy” the dispatch function and invoke a callback to notify the interested party:</p><pre>// util.js</pre><pre>export function createStore(reducer) {<br><strong>  ...</strong></pre><pre>  function Store({<br>    defaultState = {},<br>    <strong>onDispatch</strong>,<br>    children<br>  }) {<br>    const [state, <strong>baseDispatch</strong>] = React.useReducer(<br>      reducer,<br>      defaultState<br>    );</pre><pre><strong>    const dispatch = React.useCallback((action) =&gt; {<br>      baseDispatch(action);<br>      if (onDispatch) {<br>        onDispatch(action);<br>      }<br>    }, [onDispatch]);</strong></pre><pre>    return (<br>      &lt;StateContext.Provider value={state}&gt;<br>        &lt;DispatchContext.Provider value={dispatch}&gt;<br>          {children}<br>        &lt;/DispatchContext.Provider&gt;<br>      &lt;/StateContext.Provider&gt;<br>    );<br>  }</pre><pre>  ...<br>}</pre><p>Then, in the app, we simply console log actions:</p><pre>// App.js</pre><pre>...</pre><pre>export function App() {<br>  <strong>const handleDispatch = React.useCallback((action) =&gt; {<br>    console.log(action);<br>  }, []);</strong></pre><pre>  return (<br>    &lt;AppStore<br>      defaultState={defaultState}<br>      <strong>onDispatch={handleDispatch}</strong><br>    &gt;<br>      &lt;Greeter /&gt;<br>    &lt;/AppStore&gt;<br>  );<br>}</pre><p>Feel free to replace our best friend “console.log” with some fancy pants such as Splunk log. JK. Love Splunk. Anyway, this is an example of the output in Chrome:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*UE3LslVeJQSryY1pze3f8A.png" /><figcaption>Track actions in their dispatched order</figcaption></figure><h3>Inspect store state</h3><p>Store state is maintained inside React context’s provider, however, context provider is not very obvious to be found in React Developer Tools, especially in deeply nested component trees. React Developer Tools will just display a bunch of generic Context.Providers in the “component” panel like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*WAuY_RtCt5h7LDFi4IoRrA.png" /><figcaption>Too many Providers! Which is which?</figcaption></figure><p>What we want is to easily find context provider from our state store, and inspect its “value” prop, since the value prop is actually the store state.</p><p>Well, it is very easy solve this problem. The magic word is “displayName”. Pass a name to the createStore function, and assign the name to the context’s displayName:</p><pre>// util.js</pre><pre>export function createStore(<strong>name</strong>, reducer) {<br><strong>  </strong>const StateContext = React.createContext();<br>  const DispatchContext = React.createContext();<br><strong>  StateContext.displayName = `${name}State`;<br>  DispatchContext.displayName = `${name}Dispatch`;</strong></pre><pre>  ...<br>}</pre><p>For example, we name it “AppStore” when creating our state store:</p><pre>// store.js</pre><pre>...</pre><pre>const [<br>  AppStore,<br>  useAppState,<br>  useAppDispatch<br>] = createStore(<strong>&quot;AppStore&quot;</strong>, reducer);</pre><pre>export { AppStore, useAppState, useAppDispatch };</pre><p>Now, searching by the name “AppStore” in React Developer Tools will target our store:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*9gcvy2cILDXfvuxhLtfD6w.png" /><figcaption>Search by “AppStoreState” and inspect its value prop</figcaption></figure><p>Select the “AppStoreState.Provider”, and expand the “value” prop. Store’s state will be listed here. The value prop will be updated every time the store state changes. This gives us a real-time inspection of the store state. Very handy.</p><h3>Conclusion</h3><p>With React Context and hook APIs, we can leverage reducers to manage state without Redux. A single createStore function wraps 40 lines of boilerplate code. Developers only need to define the store, and use the custom React hooks to access the store. Any React user should be able to pick up this pattern quickly.</p><p>However, I am not saying this patten should be used to replace Redux 100% of the time. Some features provided by Redux such as time travel don’t exist in this alternative solution. But do you really need these features for your projects? You should ask yourself this question. For most projects, React’s built-in APIs are already capable enough to handle state management.</p><p>Here is the full source code:</p><p><a href="https://codesandbox.io/embed/elated-architecture-nupbb?fontsize=14&amp;hidenavigation=1&amp;module=%2Fsrc%2Futil.js&amp;theme=dark&amp;view=editor">elated-architecture-nupbb - CodeSandbox</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e76824fe4e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Low Cost and Highly Automated Living Style Guide]]></title>
            <link>https://davidwcai.medium.com/creating-a-low-cost-and-highly-automated-living-style-guide-a22b40eb10b?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/a22b40eb10b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[style-guides]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[living-style-guide]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Tue, 13 Feb 2018 05:22:32 GMT</pubDate>
            <atom:updated>2018-02-13T05:22:32.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GyGMSxas4zj8XHtlQyU5w.jpeg" /></figure><p>Living style guide is an essential tool for designers and developers to create re-usable components. It is a central place to demonstrate base styles, components, and modular patterns. Creating a living style guide might sound easy — it is just a HTML web page, right? Not entirely correct :) In this article I will list some of the challenges and possible solutions at a high level.</p><h4>Maintenance</h4><p>It might be surprising that the most outstanding challenge that I observed in many style guides I created is how to manage maintenance cost. Everyone loves style guide, but when it comes to maintaining one, nobody wants to do it. Why? Because it sounds like tedious and extra work :)</p><p>Naturally, I believe developers should be responsible for maintaining style guides. However, the developers who created a style guide might not be the same ones who developed components displayed in a style guide. Or simply, the developers forgot to update components in a style guide. A common scenario is like this — a style guide is showing a Button component created several months ago, even after its styles have long been changed.</p><p>For all kinds of reasons, there is high chance that components displayed in a style guide don’t reflect their latest state from development. And this single challenge is going to either make or break a style guide. If a style guide is not showing components in their high fidelity, what good use is it for?</p><p>Many of the following points I’m going to make are related to this topic — how to lower the maintenance cost.</p><h4>Demo Page</h4><p>9 out of 10 cases, if you ask developers to create demo pages in a style guide, the developer will just copy the same code from a component’s test page to the style guide. This might sound sloppy, but actually makes sense to developers. Because the component test page and the style guide demo page both serve a similar purpose — demonstrate a component’s functionality.</p><p>So if they are doing similar things, why not combine these two into one — having one single demo for a component that is used as both development sandbox and demonstration in a style guide? Popular frameworks such as <a href="https://storybook.js.org/"><em>Storybook</em></a> provides developers APIs to create sandboxes for developing components. And the storybook itself resembles a style guide. This combined effort comes with two major advantages:</p><ol><li>When developers are developing a component, they are also creating a style guide demo page at the same time. Hey, no “extra work”!</li><li>The style guide demo will always be up to date. Awesome!</li></ol><p>This is huge for reducing development and maintenance cost. A component’s demo file is used for both purposes — development and demonstration. Kill two birds with one stone, you say? Whenever a component is created or updated, its style guide page is automatically created and updated, due to the fact that the component’s test page and style guide demo page are actually the same file.</p><h4>Auto Discovery</h4><p>In my project, the style guide and the components are in one single repo. They share sources. However, how a style guide knows which component has demo and where the demo file locates?</p><p>These two lines of magical code reveals the secret:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f94a4c47a0183da6eb7335927e202c6d/href">https://medium.com/media/f94a4c47a0183da6eb7335927e202c6d/href</a></iframe><p>require.context is a <em>Webpack</em> API which dynamically resolves import paths using regex patterns. In the above code, we are starting from the parent directory (the .. part), and recursively looking for any file ending with .demo.jsx, or any index.jsx file under a demo directory. The second line imports the resolved paths.</p><p>For component developers, there is no need to register component demo page with style guide. As long as the demo pages are named after the pattern, they will be automatically loaded by the style guide. This is convention-over-configuration at its best!</p><h4>Testing</h4><p>In the “Demo Page” section, I mentioned that a demo page can be used for both development and demonstration. Actually, the same demo page can also be used for visual test (browser test).</p><p>In my project, I set up visual tests to spin up <em>Node</em> <em>Express</em> that serves the style guide pages, and run test scripts (e.g. <em>Mocha</em> and <em>Chai</em>) to automate testing components in browsers. This approach is great for two reasons:</p><ol><li>QA (or developers) are also using the same style guide.</li><li>The style guide itself is frequently tested.</li></ol><p>Now, if you hook up the visual test in a Continuous Integration (CI) pipeline, you will have high-confidence checks if anything goes wrong in a style guide.</p><p>With this single-demo-multi-usage approach, we achieved something like the following chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*uzKQdnkqQEI-9DORm3PsKQ.png" /></figure><h4>Multi Use</h4><p>A style guide is serving 3 areas at the same time — development, design, and test. It plays an essential role in web development cycles. Because of style guide’s multiple usages, it serves a shared platform for different departments to work together. To deliver a successful UX, technology is only able to achieve the 50% of the work; the other 50% depends on the collaboration among people of different roles. A living style guide brings together all involving parties as stakeholders, and speaks a common language understandable to all.</p><h4>Publishing</h4><p>Style guides need to be accessible to a wide audience. Its assets should be hosted somewhere. A Continuous Integration (CI) pipeline can be used to automate the publishing process. Having a nightly job to pull component code, generate static assets, and upload them to a central place can be a sound solution. However, what if the change is not in a master branch? What if a developer just wants to use the style guide to demonstrate a bug fix for a component?</p><p>If developers follow the GIT workflow — creating Pull Requests (PR) for each feature request or bug fix, then each PR branch should contain a set of changes related only to a feature or bug fix. To demonstrate such changes in a style guide, the guide should allow publishing component changes for a specific PR branch.</p><p>I would suggest a living style guide providing developers a command line tool. The tool does the following things:</p><ol><li>Build the code in a branch.</li><li>Bundle the static assets.</li><li>Upload the assets to a central place (e.g., AWS S3 or Github pages).</li><li>Store the assets by branch names. This allows style guide to retain changes relevant to a specific branch.</li></ol><p>Bundlers such as <em>Webpack</em> can handle point 1 and 2. For AWS S3, you can use <em>AWS CLI </em>to upload assets to a specific directory; for Github, the <a href="https://github.com/tschaub/gh-pages"><em>gh-pages</em></a> node module can be used to publish files to Github pages.</p><p>Developers now are able to publish their component work to a style guide on demand. This can be very handy for UI Acceptance Test — a developer can send designers an URL to the style guide which has the requested changes, and the designer will be able to play with the updated component in action. No more screenshot or video recording.</p><h4>Versioning</h4><p>Components can go through rapid development cycles. For the same component, its look and feel might change due to feature requests or bug fixes. How will a style guide evolve along with components?</p><p>In my project, I set CI pipeline to build, bundle, and publish style guide assets for each release tag. Whenever the CI detects a GIT commit tagged with a release version, e.g. v3.4.0 or v4.0.0-alpha.1, the CI will run the following steps:</p><ol><li>Build the code in a branch.</li><li>Bundle the static assets.</li><li>Upload the assets to a central place (e.g., AWS S3 or Github pages).</li><li>Store the assets by tag names.</li></ol><p>As you can already tell, these 4 steps are almost identical to the previous steps mentioned in the “Publishing” section, except for the 4th point where we now store the assets using tag names. All these steps allow style guide to track different versions.</p><p>The follow <em>Jenkinsfile</em> snippet checks if a commit is tagged with a release version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d28fb54a92f4a473de57197cdb7ecf75/href">https://medium.com/media/d28fb54a92f4a473de57197cdb7ecf75/href</a></iframe><h4>Conclusion</h4><p>A living style guide is not just a HTML page. It has a whole set of tools behind it to automate the development and maintenance process. It is a cross-department effort to ensure consistent look and feel across products.</p><p>Many tools can be used to reduce the friction from different roles involving in creating a living style guide. Tools like Storybook is able to re-use a single demo for multiple purposes — design, development, and test. For complicate projects, you can definitely roll your own storybook-like framework with aforementioned techniques. Actually, in my company, we use Storybook as a reference but create our own framework that gives us full control of the styles and build setup.</p><p>In our experience, a low-cost and highly automated style guide is the crucial tool to ensure high-quality components. If you are developing components, take some time to adopt a living style guide strategy. You won’t regret it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a22b40eb10b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS in JS and Test-ability]]></title>
            <link>https://davidwcai.medium.com/css-in-js-and-test-ability-4b2f6cde064?source=rss-1c7538dd8dad------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b2f6cde064</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[css-in-js]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[David Cai]]></dc:creator>
            <pubDate>Wed, 20 Dec 2017 20:34:05 GMT</pubDate>
            <atom:updated>2017-12-20T20:34:05.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*naarSglhrXdW0KZaVp7GFA.png" /></figure><p>My company is in the middle of technology migration to move closer to the React ecosystem. We seek a new styling solution to replace SASS or PostCSS in order to bring more direct interplay between React components and CSS styling. We chose Styled Components — one of the main CSS-in-JS libraries. Part of the reasons is test-ability. Many modern styling solutions try to solve the following common problems:</p><ol><li>Isolation — Encapsulate styles in scopes. Prevent styles inside and outside of the scope from polluting each other.</li><li>Utilities — Helpers to ease the calculation (e.g., darkening color), and reduce boilerplate code (e.g., adding vendor prefixes).</li><li>Reusablity — Reuse and extend defined styles.</li></ol><p>Traditional CSS pre-processing technologies (e.g., PostCSS with CSS Module) are able to solve the above problems. Even SASS with <a href="http://getbem.com/naming/">BEM</a> convention can provide a workaround solution to these problems. However, CSS-in-JS solution excels at solving another common issue — style testing.</p><h3>Test Mixins and Functions</h3><p>Here is a SASS function that maps weight names to numeric values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43d87a957c8b1140fd723f1d2e6e7ca0/href">https://medium.com/media/43d87a957c8b1140fd723f1d2e6e7ca0/href</a></iframe><p>This is all good. But how do we test this getWeight function? I am sure you can come up with some creative solutions that might leverage the SASS compiler and then inspect the produced CSS. This solution has quite some loops to jump in order to get the test going.</p><p>Now with Styled Components, getWeight is simply a JavaScript function like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6ef90cfc8b10c18b8f7a1d26fcb99e4/href">https://medium.com/media/b6ef90cfc8b10c18b8f7a1d26fcb99e4/href</a></iframe><p>And to test it is just like unit tests for any JavaScript function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11ffda263e93ba389750b8fa4bcc9443/href">https://medium.com/media/11ffda263e93ba389750b8fa4bcc9443/href</a></iframe><p>Mixins or functions are probably the lowest-level dynamic parts in style definitions. And they tend to be used a lot. It is crucial to get this base-level functionality done right. Having unit test cover these functions gave us high confidence for the styling code.</p><h3>Test Components</h3><p>We can also test a component’s styles in unit test. To continue our example, we call the getWeight function in a Styled Component – StyledDiv in which we define the font-weight style; then a React component FontWeight wraps its children with StyledDiv:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/935e0b4519352410c5f010ffb0f55f5e/href">https://medium.com/media/935e0b4519352410c5f010ffb0f55f5e/href</a></iframe><p>Styled component translates interpolated strings to CSS styles, and create CSS classes. Tools such as <a href="https://github.com/styled-components/jest-styled-components">jest-styled-components</a> can be used to inspect the translated CSS styles. This gives us an easy way to test component styles in unit test.</p><p>Here is an example. We test if a FontWeight component has font-weight: 300 when its weight prop is set to ‘light’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29c4f32d42a9686ade231a2aa948156f/href">https://medium.com/media/29c4f32d42a9686ade231a2aa948156f/href</a></iframe><p>toHaveStyleRule gives us fine granular assertions over a component’s internal styles. This makes it much easier for unit test to verify styles. Unit tests are way faster than visual acceptance tests which often rely on browsers or engines to render components in DOMs. With the capability of having style verification in unit test, we can conduct more extensive style tests without relying on slow acceptance tests. That is not to say acceptance test should be replaced by style unit test, but having unit test cover all corner cases make it possible for acceptance test to focus on critical-path scenarios, which results in less acceptance test code and shorter pipeline build time.</p><p>I have to mention another API from jest-styled-components toMatchSnapshot because it is amazing. toMatchSnapshot takes a snapshot of a component’s structure and its styles, and compares the snapshot with previously saved one. If there is any difference, the assertion will fail and a diff will be output.</p><p>For instance, the toMatchSnapshot call in the following test spec will capture FontWeight component’s DOM structure and styles in a snapshot file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/774240fd45ab6e7cc62177b92d26a2a9/href">https://medium.com/media/774240fd45ab6e7cc62177b92d26a2a9/href</a></iframe><p>Running the above test spec for the first time will produce a snapshot file like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb40aef294e59613da2b3b39bacd326c/href">https://medium.com/media/eb40aef294e59613da2b3b39bacd326c/href</a></iframe><p>If anything goes wrong (e.g., font-weight becomes 200), running the same test will produce a diff in terminal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f05448c501936a906a9b6fd34009346d/href">https://medium.com/media/f05448c501936a906a9b6fd34009346d/href</a></iframe><p>The diff provides us a straightforward way to spot what changes and what was the original. Quite handy when you just want to make sure that no style will accidentally get changed.</p><h3>Conclusion</h3><p>We are quite happy about the adoption Styled Components. CSS in JS not only solves common styling problems, but more importantly for us, it makes unit test for components pleasant again. We are able to write more useful style tests with much less effort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b2f6cde064" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>