<?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 Josh Heling on Medium]]></title>
        <description><![CDATA[Stories by Josh Heling on Medium]]></description>
        <link>https://medium.com/@jrheling?source=rss-f32c9b464339------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*YKEXrkXo3QoArIgvFo5HIQ.jpeg</url>
            <title>Stories by Josh Heling on Medium</title>
            <link>https://medium.com/@jrheling?source=rss-f32c9b464339------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:40:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jrheling/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[Using Serverless Framework with the Amplify Client Library]]></title>
            <link>https://medium.com/@jrheling/using-serverless-framework-with-the-amplify-client-library-9f3a1e2ee24f?source=rss-f32c9b464339------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f3a1e2ee24f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Josh Heling]]></dc:creator>
            <pubDate>Tue, 03 Mar 2020 23:39:40 GMT</pubDate>
            <atom:updated>2020-03-07T16:51:37.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="logos for AWS Amplify, Python, and Serverless Framework" src="https://cdn-images-1.medium.com/max/241/1*DAsi47CCJ5Tjox4EfkpidQ.png" /></figure><p><strong>This article describes a relatively easy way to use AWS’ Amplify client library to build a serverless app <em>when your backend includes python functions</em>.</strong></p><p>Amplify is an AWS product that offers an attractive way to simplify development in some common application scenarios. It includes:</p><ul><li>Client libraries for common frontend frameworks (React, Angular, Ionic, Vue).</li><li>A CLI that simplifies provisioning and managing AWS-based backend infrastructure.</li><li>Glue that connects the frontend and backend.</li></ul><p><a href="https://aws-amplify.github.io/docs/">AWS’ docs for Amplify</a> are pretty good, and include step-by-step tutorials (e.g. <a href="https://aws-amplify.github.io/docs/js/react">this one for React</a>) that will get you up and running quickly in many cases.</p><p>Like all batteries-included frameworks, though, there’s a catch. In this case, the detail that caught me was that <strong>Amplify’s CLI only supports backend AWS Lambda functions written in javascript</strong>.</p><p>Amazon is <a href="https://github.com/aws-amplify/amplify-cli/issues/156">working on removing this limitation</a>, but in the meantime I needed a mostly Python backend for a project. I still wanted to take advantage of the Amplify library on the frontend, and liked the idea of automating things like authz around my backend API (which Amplify does).</p><p><a href="https://serverless.com/">Serverless Framework</a> provides a well-known way to simplify deployment of backend bits to AWS (and other cloud providers). It covers similar ground as the CLI part of Amplify, and I knew I could express my desired backend resources using it.</p><p>And the Amplify client libraries work fine on their own. So that covers two of the three things Amplify provides.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piT2mji9jD6m0X3VTg1mTA.jpeg" /></figure><p>It’s possible to connect the Amplify client library with the resources provisioned via Serverless Framework via manual configuration, an approach which is detailed in <a href="https://serverless-stack.com/chapters/configure-aws-amplify.html">Serverless’ documentation</a>. While this works, it’s pretty brittle, and would require managing different configs for different operating environments, and involve manual work to update the frontend after a new Serverless deployment.</p><p>I wanted something closer to the single sourced frontend+backend configuration one gets when using Amplify by itself. Fortunately, I’m not the only one with this desire — Amazon maintains <a href="https://github.com/awslabs/aws-amplify-serverless-plugin">a Serverless plugin that generates Amplify config files</a>. Perfect! That’s just the thing I needed, really.</p><p>To recap, what this amounts to is replacing the backend-related use of the Amplify CLI in this project with a combination of Serverless Framework and the aws-amplify-serverless plugin. The Amplify CLI is still used for the frontend hosting / deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_EuNOBTI5iQkuwXXdksQA.jpeg" /></figure><p>The React app in the frontend will use Amplify’s React library, and I’ll be able to use Serverless to connect it (via the plugin) to my python functions. We’ll use AWS Cognito, too, so that only logged in users can access our backend API.</p><p>Conceptually, this is straightforward. In practice, it isn’t exactly difficult, but there were a few details that weren’t quite obvious to me at first.<strong> The rest of this article describes the step-by-step required to get this set up. </strong>Source code for the proof-of-concept outline below is in <a href="https://github.com/jrheling/amplify-react-serverless-example">this repo</a>.</p><h3>Step 1: Amplify Installation &amp; Configuration</h3><p>First, we’ll need the Amplify CLI installed: npm install -g @aws-amplify/cli.</p><p>The amplify configure command will spawn a browser window to associate the project with an AWS account, and then prompt for some basic settings. It prompts to create a user for Amplify to run as (make sure to take note of the Access Key ID and Secret Access Key), and creates a new AWS profile associated with the newly created user:</p><pre>Sign in to your AWS administrator account:<br><a href="https://console.aws.amazon.com/">https://console.aws.amazon.com/</a><br>Press Enter to continue</pre><pre>Specify the AWS Region<br>? region:  us-west-2<br>Specify the username of the new IAM user:<br>? user name:  amplify-sls-example-user<br>Complete the user creation using the AWS console<br><a href="https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&amp;accessKey&amp;userNames=amplify-sls-example-user&amp;permissionType=policies&amp;policies=arn:aws:iam::aws:policy%2FAdministratorAccess">https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&amp;accessKey&amp;userNames=amplify-sls-example-user&amp;permissionType=policies&amp;policies=arn:aws:iam::aws:policy%2FAdministratorAccess</a><br>Press Enter to continue</pre><pre>Enter the access key of the newly created user:<br>? accessKeyId:  **********<br>? secretAccessKey:  ********************<br>This would update/create the AWS Profile in your local machine<br>? Profile Name:  amplify-sls-example</pre><pre>Successfully set up the new user.</pre><h3>Step 2: Basic Frontend App</h3><p>Now we’ll set up a barebones React app. For this demonstration, the familiar CRA placeholder app will work fine, but there’s nothing CRA-specific we depend on. While these instructions assume React, a similar approach should work for <a href="https://aws-amplify.github.io/docs/js/start">any of the other frontends Amplify supports</a>.</p><pre>$ npx create-react-app amplify-react-serverless-example<br>...<br>Happy hacking!<br>$ </pre><p>Initialize amplify with amplify init — use values that make sense for you, but make sure to choose ‘javascript’ for app type:</p><pre>$ amplify init<br>Note: It is recommended to run this command from the root of your app directory<br>? Enter a name for the project ampl-sls-example<br>? Enter a name for the environment dev<br>? Choose your default editor: Visual Studio Code<br>? Choose the type of app that you&#39;re building javascript<br>Please tell us about your project<br>? What javascript framework are you using react<br>? Source Directory Path:  src<br>? Distribution Directory Path: build<br>? Build Command:  npm run-script build<br>? Start Command: npm run-script start<br>Using default provider  awscloudformation</pre><pre>For more information on AWS Profiles, see:<br><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html">https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html</a></pre><pre>? Do you want to use an AWS profile? Yes<br>? Please choose the profile you want to use amplify-sls-example<br>Adding backend environment dev to AWS Amplify Console app: d39ymvscqz4gs5<br>⠴ Initializing project in the cloud...<br>...<br>Your project has been successfully initialized and connected to the cloud!<br>...<br>$ </pre><p>Add frontend hosting with amplify add hosting. Choose the “DEV” option for now and the default options for the other choices, then run amplify publish to see the vanilla CRA template running.</p><p>So far these instructions have directly tracked <a href="https://aws-amplify.github.io/docs/js/react">AWS’ docs</a> (with less detail) — we diverge from them starting in the next section.</p><h3>Step 3: Serverless Framework Skeleton</h3><p>Eventually, we’re going to deploy a backend API, and of course we don’t want just anybody to be able to access it. Before we can limit access to our API to logged-in users, though, we need users to be able to log in.</p><p>If we were using Amplify for the entire project (like the AWS docs assume), we’d use the amplify command to add an auth backend component. But instead we’re going to define our backend using Serverless Framework. Let’s get that scaffolded out, and then we’ll add auth to it in the next step.</p><p>Installing Serverless Framework is as easy as npm install -g serverless (more details <a href="https://serverless.com/framework/docs/providers/aws/guide/quick-start/">here</a>).</p><p>We need some Serverless plugins, too:</p><pre>$ yarn add -D serverless-wsgi serverless-python-requirements aws-amplify-serverless-plugin</pre><p>Let’s put a very basic serverless.yml in place, so we start to see how this will come together:</p><pre># serverless.yml<br>service: ampl-sls-example-backend</pre><pre>plugins:<br>- aws-amplify-serverless-plugin</pre><pre>custom:<br>  stage: ${opt:stage, &quot;dev&quot;}<br>  pythonRequirements:<br>    dockerizePip: non-linux<br>  amplify:<br>    # this can be anything, as long as the frontend project includes it<br>    - filename: src/aws-exports.js<br>      type: javascript</pre><pre>package:<br>  exclude:<br>    - node_modules/**<br>    - amplify/**<br>    - public/**<br>    - src/**<br>    - yarn.lock</pre><pre>provider:<br>  name: aws<br>  stage: ${self:custom.stage}<br>  region: us-west-2</pre><p>For those both attentive and curious: The package section here is needed because we have both the frontend and backend coming from the same project, but <em>don’t</em> want to include all the frontend dependencies in the backend artifact.</p><p>Deploy this skeleton of our eventual backend with AWS_PROFILE=amplify-sls-example sls deploy. Note that we’re specifying the AWS profile created in step 2 above via the environment (the Serverless docs detail <a href="https://serverless.com/framework/docs/providers/aws/guide/credentials/">other ways to do this </a>— how you choose to specify the profile isn’t important, but using the right profile is).</p><p>The Serverless deploy should look something like this:</p><pre>$ AWS_PROFILE=amplify-sls-example sls deploy<br>Serverless: Packaging service...<br>Serverless: Creating Stack...<br>Serverless: Checking Stack create progress...<br>.....<br>Serverless: Stack create finished...<br>Serverless: Uploading CloudFormation file to S3...<br>Serverless: Uploading artifacts...<br>Serverless: Validating template...<br>Serverless: Updating Stack...<br>Service Information<br>service: ampl-sls-example-backend<br>stage: dev<br>region: us-west-2<br>stack: ampl-sls-example-backend-dev<br>resources: 1<br>api keys:<br>  None<br>endpoints:<br>  None<br>functions:<br>  None<br>layers:<br>  None</pre><p>There’s really nothing there yet, because we haven’t actually asked Serverless to deploy anything, <em>but</em> this shows us that the serverless.yml is valid. More importantly, if we look at the src/aws-export.js file, we can see that the aws-amplify-serverless-plugin is doing its thing and exporting the bits of configuration that the client side of Amplify will need into a simple js structure ready for import:</p><pre>$ cat src/aws-exports.js<br>// WARNING: DO NOT EDIT.  This file is automatically generated<br>// Written by aws-amplify-serverless-plugin/1.4.1 </pre><pre>const awsmobile = {<br>    aws_project_region: &#39;us-west-2&#39;<br>};</pre><pre>export default awsmobile;<br>$</pre><p>Right now that’s pretty much nothing, but as we add substance to the Serverless project this file will be the glue that connects our Serverless-defined backend resources to the Amplify client library in our frontend React app.</p><h3>Step 4: Adding Auth — Backend</h3><p>We’re going to extend our serverless.yml file to define both a Cognito User Pool and an Identity Pool, which provide authentication and authorization, respectively. (Cognito concepts are covered in appropriate depth <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html">elsewhere</a> — this just includes the basics needed to get started.)</p><p>It’s possible to define the User and Identity Pools directly in the serverless.yml, but they’re fairly verbose, so it’s nice to keep them in separate files and include them by reference. We’ll mkdir resources to give them a place to live, and then put these files in resources/:</p><ul><li><a href="https://github.com/jrheling/amplify-react-serverless-example/blob/master/resources/cognito-identity-pool.yml">cognito-identity-pool.yml</a></li><li><a href="https://github.com/jrheling/amplify-react-serverless-example/blob/master/resources/cognito-user-pool.yml">cognito-user-pool.yml</a></li></ul><p>And then reference them from the serverless.yml:</p><pre>...<br>resources:<br>  - ${file(resources/cognito-user-pool.yml)}<br>  - ${file(resources/cognito-identity-pool.yml)}</pre><p>Unfortunately, we can’t yet demonstrate that this is doing anything, because the policies attached to the Identity Pool reference an API Gateway we haven’t yet set up.</p><p>Let’s fix that!</p><h3>Step 5: Create the Backend API</h3><p>For the sake of this tutorial we’re going to define an absurdly trivial API endpoint. We literally just need <em>something</em> that we can call in order to demonstrate that only authenticated users are able to successfully interact with the API.</p><p>A few python dependencies are needed, so take a moment to initialize a virtualenv, switch to it, and install flask and CORS support:</p><pre>## change this path to whevever you keep your venvs<br>$ mkvirtualenv ~/.virtualenvs/amplify-react-sls   <br>...<br>$ workon amplify-react-sls<br>$ pip install flask Flask-CORS<br>## this is important so that serverless knows what deps to bundle <br>$ pip freeze &gt; requirements.txt</pre><p>And then create app.py:</p><pre># app.py<br>from flask import Flask<br>from flask_cors import CORS<br>app = Flask(__name__)<br>CORS(app)</pre><pre>@app.route(&quot;/test&quot;)<br>def hello():<br>  return &quot;You must have authenticated correctly.&quot;</pre><p>Our serverless.yml changes in a few places to make this work — here’s what the whole file should look like now:</p><pre># serverless.yml<br>service: ampl-sls-example-backend</pre><pre>plugins:<br>  - serverless-python-requirements<br>  - serverless-wsgi<br>  - aws-amplify-serverless-plugin</pre><pre>custom:<br>  stage: ${opt:stage, &quot;dev&quot;}<br>  wsgi:<br>    app: app.app<br>    packRequirements: false<br>  pythonRequirements:<br>    dockerizePip: non-linux<br>  amplify:<br>    # this can be anything, as long as the frontend project includes it<br>    - filename: src/aws-exports.js<br>      type: javascript<br>      appClient: CognitoUserPoolClient</pre><pre>package:<br>  exclude:<br>    - node_modules/**<br>    - amplify/**<br>    - public/**<br>    - src/**<br>    - yarn.lock</pre><pre>provider:<br>  name: aws<br>  runtime: python3.6<br>  stage: ${self:custom.stage}<br>  region: us-west-2</pre><pre>functions:<br>  app:<br>    handler: wsgi_handler.handler<br>    events:<br>      - http:<br>         path: /test<br>         method: any<br>         cors: true<br>         authorizer: aws_iam</pre><pre>resources:<br>  - ${file(resources/cognito-user-pool.yml)}<br>  - ${file(resources/cognito-identity-pool.yml)}</pre><p>Most of these changes are standard Serverless config (see <a href="https://serverless.com/blog/flask-python-rest-api-serverless-lambda-dynamodb/">this</a> for explanation of most of it). The new appClient section in custom.amplify is important — it references the User Pool client we created above, which is an essential step in getting its config details to be included in the src/aws-exports.js file. The aws_iam line in the function definition is also important; that tells the API Gateway that will be created to require auth for calls to /test.</p><p>If we now run sls deploy again, a lot more will happen:</p><pre>$ AWS_PROFILE=amplify-sls-example sls deploy<br>...<br>Serverless: Stack update finished...<br>Service Information<br>service: ampl-sls-example-backend<br>stage: dev<br>region: us-west-2<br>stack: ampl-sls-example-backend-dev<br>resources: 17<br>api keys:<br>  None<br>endpoints:<br>  ANY - <a href="https://elpcxo65f9.execute-api.us-west-2.amazonaws.com/dev/test">https://elpcxo65f9.execute-api.us-west-2.amazonaws.com/dev/test</a><br>functions:<br>  app: ampl-sls-example-backend-dev-app<br>layers:<br>  None</pre><p>And a correspondingly larger set of config data is in src/aws-exports.js, ready to be imported by the React app:</p><pre>$ cat src/aws-exports.js<br>// WARNING: DO NOT EDIT.  This file is automatically generated<br>// Written by aws-amplify-serverless-plugin/1.4.1 </pre><pre>const awsmobile = {<br>    aws_cloud_logic_custom: [<br>        {<br>            endpoint: &#39;<a href="https://elpcxo65f9.execute-api.us-west-2.amazonaws.com/dev&#39;">https://elpcxo65f9.execute-api.us-west-2.amazonaws.com/dev&#39;</a>,<br>            name: &#39;ApiGatewayRestApi&#39;,<br>            region: &#39;us-west-2&#39;<br>        }<br>    ],<br>    aws_cognito_identity_pool_id: &#39;us-west-2:a0a03944-b40b-4d4a-90b0-caf46deda1e5&#39;,<br>    aws_cognito_region: &#39;us-west-2&#39;,<br>    aws_project_region: &#39;us-west-2&#39;,<br>    aws_user_pools_id: &#39;us-west-2_m1yz5KHFQ&#39;,<br>    aws_user_pools_web_client_id: &#39;3gntaunleuo30e8mem40laomv&#39;<br>};</pre><pre>export default awsmobile;</pre><p>Our new backend API endpoint now exists in AWS’ API Gateway, backed by a lambda function built from app.py. And we can validate that auth is being required with curl:</p><pre>$ curl  <a href="https://elpcxo65f9.execute-api.us-west-2.amazonaws.com/dev/test">https://elpcxo65f9.execute-api.us-west-2.amazonaws.com/dev/test</a><br>{&quot;message&quot;:&quot;Missing Authentication Token&quot;}</pre><p>We expected this error, of course, since we require auth on the endpoint but didn’t provide any in the curl request.</p><p>So the backend is largely in place now, configured by Serverless Framework. Time to get the React app talking to it!</p><h3>Step 6: Add Amplify Auth to React</h3><p>First, let’s integrate our React app with the the Cognito backend resources we set up in step 4. When we’re done with this step, accessing our CRA template will require login. (Of course, this by itself isn’t very interesting, but it’s an important prerequisite to protecting the backend API.)</p><p>(Note: this section pretty much mirrors the React side of the <a href="https://aws-amplify.github.io/docs/js/react#add-auth">AWS docs </a>— check them out for a more detailed step-by-step.)</p><p>Add the amplify-related dependencies:</p><pre>$ yarn add aws-amplify aws-amplify-react</pre><p>and then import them into src/App.js:</p><pre>import Amplify from &#39;aws-amplify&#39;;<br>// file generated by the sls plugin<br>import awsconfig from &#39;./aws-exports&#39;;<br>import { withAuthenticator } from &#39;aws-amplify-react&#39;;</pre><p>And then initialize Amplify with the details exported from our Serverless config (by the aws-amplify-serverless plugin):</p><pre>Amplify.configure(awsconfig);</pre><p>For now we’ll leave the App() function as-is, but change the export line to wrap it with the withAuthenticator HOC, which will force valid authenticator before rendering App:</p><pre>export default withAuthenticator(App, true);</pre><p>Re-build and re-deploy the frontend (with amplify publish), and you should find yourself looking at an authentication prompt rather than the stock CRA template:</p><figure><img alt="Screenshot of default Amplify login screen" src="https://cdn-images-1.medium.com/max/898/1*hEFGh30e5QbTvUag-CMYUQ.png" /></figure><p>OK, cool — we wanted to require logins, so this is progress. To create a user, head over the Cognito section of your AWS console, and choose User Pools. You should see a pool whose name corresponds to the service and stage defined in your serverless.yml, like this:</p><figure><img alt="Screenshot of AWS console User Pools view" src="https://cdn-images-1.medium.com/max/503/1*sw2975kaHIVlubdGIvQaiQ.png" /></figure><p>Select that pool, then choose “Users and groups” from the left-hand nav rail, and then “Create user”. Go through the user creation process, and use the username/password you created to log in to your deployed app.</p><p>On the one hand, this looks like no big deal — it’s just the CRA template app running behind a generic login window. While that’s not so exciting by itself, this is proof that our app now has a backend auth store that our React app knows about. <strong>We’ll use that in the next step to make sure only authenticated users can access our backend API</strong>.</p><p>(For the sake of demonstrating the core thing this article is about, I’m glossing over all kinds of details you can tweak: user account attributes, login form style, and account-related controls in the app once you’ve logged in, just to name a few. See the Amplify docs for more detail.)</p><h3>Step 7: Call the API</h3><p>We’re almost there — all that’s left is to wire up our API into the React app in order to demonstrate that the auth credentials our React app gets from logging in are what the API Gateway in front of our backend API is expecting.</p><p>First, add the API module to our imports from aws-amplify:</p><pre>// App.js<br>...<br>import Amplify, { API } from &#39;aws-amplify&#39;;</pre><p>Then we’ll add a function that calls the API:</p><pre>function App() {<br>  const get = async () =&gt; {<br>    console.log(&#39;calling GET&#39;);<br>    const response = await API.get(<br>      &#39;ApiGatewayRestApi&#39;, // function defined in our serverless.yml<br>      &#39;/test&#39;,            // the function&#39;s path<br>      { &#39;responseType&#39;: &#39;text&#39; }<br>    );<br>    console.log(`got ${response}`);<br>    alert(response);<br>  };</pre><pre>  ...</pre><p>and add a crude way to trigger the function to the return statement:</p><pre>...<br>    Learn React<br>   &lt;/a&gt;<br>   &lt;button onClick={get}&gt;GET&lt;/button&gt;<br>  &lt;/header&gt;<br>...</pre><p>After one more amplify publish, you should see a “GET” button that, when clicked, calls our (authentication-required) API. Voila!</p><h3>Step 8: CORS for Errors</h3><p>It looks like everything’s working, but there’s one little detail we still need to cover. While the cors: true line in serverless.yml&#39;s function definition and the Flask-CORS middleware in app.py together handle the appropriate CORS headers for our backend function, we need to make sure there are CORS headers on errors (potentially) returned from the API Gateway, too. Without this step, instead of any actual error detail we’ll just get a generic CORS error in the console, which isn’t very helpful.</p><p>Fortunately, the fix is easy — just include <a href="https://github.com/jrheling/amplify-react-serverless-example/blob/master/resources/api-gateway-errors.yml">this file</a> in the resources: section of serverless.yml:</p><pre>resources:<br>  - ${file(resources/cognito-user-pool.yml)}<br>  - ${file(resources/cognito-identity-pool.yml)}<br>  - ${file(resources/api-gateway-errors.yml)}</pre><p>(This is explained in more detail <a href="https://serverless-stack.com/chapters/handle-api-gateway-cors-errors.html">here</a>.)</p><h3>Wrapping Up</h3><p>We’ve done it! Using aws-amplify-serverless-plugin, we connected an AWS backend defined with Serverless Framework to a React front-end, while keeping configuration of the details automatic.</p><p>This is just a very basic example of what can be done with these tools. While this simple app just had a single backend lambda function, it’s easy to also define DynamoDB resources, or S3 support, or use AWS’ AppSync for GraphQL support. And both Amplify and Serverless offer dashboards that can drive CI/CD.</p><p>Thanks for reading — now go build something cool.</p><figure><img alt="logos for AWS Amplify, Python, and Serverless Framework" src="https://cdn-images-1.medium.com/max/687/1*PYALKhRphiNm74lrowaQ-Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f3a1e2ee24f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Components with Hooks using Enzyme]]></title>
            <link>https://medium.com/@jrheling/testing-react-components-with-hooks-using-enzyme-fa162fc35f9e?source=rss-f32c9b464339------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa162fc35f9e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Josh Heling]]></dc:creator>
            <pubDate>Sat, 15 Feb 2020 21:41:02 GMT</pubDate>
            <atom:updated>2020-02-15T21:41:02.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*b2CHEqXyxiqcXOacMV3NYw.jpeg" /></figure><p>I’m working on a React / Redux / <a href="https://material-ui.com/">Material-UI</a> project that I had originally implemented with class-based components (in typescript). I wanted to evaluate what would be involved in moving to React Hooks, so took a few hours to test converting a handful of components.</p><p>The actual conversion was quite straightforward, thanks to good <a href="https://reactjs.org/docs/hooks-intro.html">docs</a> and helpful guides like <a href="https://medium.com/@olinations/10-steps-to-convert-a-react-class-component-to-a-functional-component-with-hooks-ab198e0fa139">this</a> and <a href="https://codersera.com/blog/react-redux-hooks-with-typescript/">this</a>. At a first glance, the hook-based components had less (and clearer) boilerplate (this was especially true with Material-UI’s styling). Just as I’d hoped.</p><p>Things got a bit more involved when I when to update my Jest/Enzyme unit tests. <strong>This article outlines the issues I had to work through, and the eventual solution I found</strong>. Based on the various github issues, StackOverflow questions, and blog posts I encountered while working through this, it’s a somewhat common area of confusion.</p><p>My original class-based components looked roughly like this:</p><pre>// components/foo.tsx<br>import * as React from &#39;react&#39;;<br>import * as actions from &#39;../store/actions&#39;;<br>import { StoreState } from &#39;../store/types&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { Dispatch } from &#39;redux&#39;;<br>import { withStyles, WithStyles, createStyles } from &#39;@material-ui/core/styles&#39;;</pre><pre>const styles = createStyles({<br>  myclass: {<br>    height: &#39;100%&#39;<br>  }<br>});</pre><pre>interface FooProps extends WithStyles&lt;typeof styles&gt; {<br>  bar: string;<br>}</pre><pre>function mapStateToProps(state: StoreState) {<br>  ...<br>}<br>function mapDispatchToProps(dispatch: Dispatch&lt;actions.AnyAction&gt;) {<br>  ...<br>}</pre><pre>const FooComponent = withStyles(styles)(<br>  class extends React.Component&lt;FooProps, {}&gt; {<br>    ...<br>    render() {<br>      return (<br>        &lt;div className={this.props.classes.myclass}&gt;<br>          ...<br>        &lt;/div&gt;<br>      )<br>    }<br>  }<br>)</pre><pre>export const Foo = connect(mapStateToProps, mapDispatchToProps)(FooComponent);</pre><p>Writing unit tests for these components was easy — I could just import the unconnected component (FooComponent, in the above example) and feed it whatever props I needed for a given test:</p><pre>// tests/foo.test.tsx<br>import * as React from &#39;react&#39;;<br>import * as enzyme from &#39;enzyme&#39;;<br>import Adapter from &#39;enzyme-adapter-react-16&#39;;<br>import { createShallow }  from &#39;@material-ui/core/test-utils&#39;;<br>import { FooComponent, Foo } from &#39;../../components/Foo&#39;;</pre><pre>enzyme.configure({ adapter: new Adapter() });</pre><pre>describe(&#39;&lt;FooComponent /&gt;&#39;, () =&gt; {<br>  let shallow: typeof enzyme.shallow;<br>  beforeEach(() =&gt; {<br>    shallow = createShallow();<br>  });</pre><pre>  it(&#39;passes &quot;bar&quot; property down&#39;, () =&gt; {<br>    const wrapper = shallow(<br>      &lt;FooComponent <br>        bar=&quot;baz&quot;<br>        ... other props ...<br>      /&gt;<br>    );<br>  expect(wrapper.children().text()).toContain(&quot;baz&quot;);<br>  });<br>});</pre><p>The test can focus on the component without regard for state management — the test doesn’t even know that Redux is involved.</p><p>After reworking the components to use hooks, they look like this:</p><pre>// components/foo.tsx<br>import * as React from &#39;react&#39;;<br>import { useSelector } from &#39;react-redux&#39;;<br>import { StoreState } from &#39;../store/types&#39;;</pre><pre>interface Props {};<br>interface FooProps {<br>  bar: string;<br>}</pre><pre>export const Foo: React.FC&lt;Props&gt; = () =&gt; {<br>  const {bar} = useSelector&lt;StoreState, FooProps&gt;((state: StoreState) =&gt; {<br>    return {<br>      bar: state.bar // obviously a trivial example<br>    }<br>  })<br>  <br>  return (<br>    &lt;div className={classes.myclass}&gt;...&lt;/div&gt;<br>  )<br>}</pre><p>Looking at the function component compared to its class-based predecessor, things are more direct and to the point.</p><p>But <strong>here’s the problem</strong>: now there’s no unconnected component I can test against. Additionally, the component no longer exposes props for the data provided by redux.</p><p>One possible solution is to import configureMockStore from redux-mock-store and wrap the component under test with a Provider that uses your mocked store:</p><pre>...<br>import configureMockStore from &#39;redux-mock-store&#39;;<br>...<br>const mockStore = configureMockStore();</pre><pre>describe(&#39;&lt;Foo /&gt;&#39;, () =&gt; {<br>  ...<br>  it(&#39;can be tested with a mocked store&#39;, () =&gt; {<br>    const store = mockStore({<br>      bar: &quot;baz&quot;<br>    })<br>  const wrapper = mount(&lt;Provider store={store}&gt;&lt;Foo/&gt;&lt;/Provider&gt;);<br>  ...</pre><p><em>This totally works</em>, and if you want mount()-based tests, this might be fine. I wanted tests that could work with shallow(), though, because a) I’m persuaded by the use-shallow-unless-you-can’t approach to component unit testing, and b) some of my already-written tests didn’t work with with mount().</p><p>A different approach is needed to test with shallow(). (It’s tempting to think that’s as simple as shallow(&lt;Provider store={store}&gt;&lt;Foo/&gt;...), but that won’t actually render Foo, because Provider ends up being the top-level component.) The solution that I liked best was to mock useSelector() and specify its return object in the test — this was functionally very close to the old prop-based approach I used before moving to hooks:</p><pre>import * as React from &#39;react&#39;;<br>import * as enzyme from &#39;enzyme&#39;;<br>import Adapter from &#39;enzyme-adapter-react-16&#39;;<br>import { createShallow }  from &#39;@material-ui/core/test-utils&#39;;<br>import { Foo } from &#39;../../components/Foo&#39;;<br>import * as Redux from &#39;react-redux&#39;;</pre><pre>enzyme.configure({ adapter: new Adapter() });</pre><pre>describe(&#39;&lt;Foo /&gt;&#39;, () =&gt; {<br>  let shallow:typeof enzyme.shallow;<br>  let useSelectorSpy: jest.SpyInstance;</pre><pre>  beforeEach( () =&gt; {<br>    shallow = createShallow();<br>    useSelectorSpy = jest.spyOn(Redux, &#39;useSelector&#39;);<br>  })</pre><pre>  it(&#39;should work&#39;, () =&gt; {<br>    useSelectorSpy.mockReturnValue({<br>      bar: &#39;baz&#39;<br>    })</pre><pre>  const wrapper = shallow(&lt;Foo/&gt;);<br>  expect(wrapper.is(Foo));<br>  });<br>});</pre><p>If your component uses useState() but does <em>not</em> use useDispatch(), then the above should be all you need. If you are also using useDispatch() then you’ll get an error like:</p><blockquote>Invariant Violation: could not find react-redux context value; please ensure<br> the component is wrapped in a &lt;Provider&gt;</blockquote><p>This makes sense, since the default implementation of useDispatch() ends up looking for a Context that we haven’t provided. The solution is to also mock useDispatch() — at the moment no tests are using it, so I just need enough of a mock to satisfy the transpiler and allow the component function to execute:</p><pre>import { Action } from &#39;redux&#39;;<br>...<br>describe(&#39;&lt;Foo /&gt;&#39;, () =&gt; {<br>  let shallow:typeof enzyme.shallow;<br>  let useSelectorSpy: jest.SpyInstance;<br>  let useDispatchSpy: jest.SpyInstance;</pre><pre>  beforeEach( () =&gt; {<br>    shallow = createShallow();<br>    useSelectorSpy = jest.spyOn(Redux, &#39;useSelector&#39;);<br>    useDispatchSpy = jest.spyOn(Redux, &#39;useDispatch&#39;);<br>    useDispatchSpy.mockImplementation( () =&gt; (cb: Action) =&gt; (cb));<br>  })<br>  ... </pre><p>Voila. It’s now pretty much mechanical and nearly trivial to convert old test suites to work with hook-based components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa162fc35f9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[53 Thoughts for my Fellow American People on the Occasion of the Inauguration of Donald Trump]]></title>
            <link>https://medium.com/@jrheling/53-thoughts-for-my-fellow-american-people-on-the-occasion-of-the-inauguration-of-donald-trump-d3afc37b8c43?source=rss-f32c9b464339------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3afc37b8c43</guid>
            <category><![CDATA[2016-election]]></category>
            <category><![CDATA[politics]]></category>
            <dc:creator><![CDATA[Josh Heling]]></dc:creator>
            <pubDate>Fri, 20 Jan 2017 12:23:57 GMT</pubDate>
            <atom:updated>2017-01-20T12:23:57.996Z</atom:updated>
            <content:encoded><![CDATA[<p>53 Thoughts for my Fellow American People on the Occasion of the Inauguration of Donald Trump</p><ol><li>Nothing Hillary Clinton did, maybe did, didn’t do, or should have done really matters anymore.</li></ol><p>2. The job of the media is not to serve as a megaphone for those in power.</p><p>3. The established media would not exist without its roots in old leases on our collective property. These leases were paid for in part with a commitment to inform the people and to function as another check and balance on excessive government power.</p><p>4. Without a real exchange of information and constant challenge from an adversarial press, nothing exists to stop unchecked abuses of power.</p><p>5. Twitter is not a substitute for a news conference.</p><p>6. Our new president has not done anything in his life to help anyone but himself. That doesn’t mean he can’t start now, but it’s worth keeping in mind.</p><p>7. No mechanism exists to prevent this administration from warping policy and messaging to Trump’s private gain.</p><p>8. And we don’t even have a way to recognize that it is happening.</p><p>9. We have a strong public space. Official meetings in a private golden palace are not normal.</p><p>10. “Trust me” does not resolve conflicts of interest.</p><p>11. There’s no relationship between success accumulating money and ability to run the government.</p><p>12. Continued discussion of the the reasons Trump shouldn’t have won will sound like whining to everybody who doesn’t already strongly agree with you.</p><p>13. Unless they can cause impeachment, your thoughts about Debbie Wasserman Schulz, Comey, fake news, and Putin are not relevant to day-to-day life in the Trump presidency nor to an effective response to its policy proposals.</p><p>14. The range of political views Americans have do not fit into two neat buckets labeled “Democrat” and “Republican”.</p><p>15. Those who identify strongly as “Republican” should remember that — until it was very recently convenient — Trump did not.</p><p>16. We regular people have a great deal more in common with each other than we do with our political leaders. For most Americans, a trip to the grocery store — or maybe one in a neighboring zip code — is all it would take to encounter a bunch of people who don’t seem like horrible individuals yet who voted differently than you did.</p><p>17. And most of them did it with good intentions and a sincere belief they were doing the right thing.</p><p>18. Try to persuade them to see things as you do if you want, but do it civilly. Few are persuaded by name-calling and vitriol.</p><p>19. Persuading some people is going to make the future better faster.</p><p>20. Other people’s genitals should only be grabbed in ways they desire.</p><p>21. When our leaders fail to uphold standards of basic human decency, we can still do so.</p><p>22. And hold them to account for their failures.</p><p>23. Our values cannot give way in times of crisis. That’s when we need them most.</p><p>24. Martin Niemöller had an important point with “First they came…”</p><p>25. A vote is not a pledge. If you voted for Trump, that doesn’t mean you’re obliged to support everything he does.</p><p>26. If you voted for him as the less-bad of two choices you didn’t like, or while “holding your nose” about some aspect of him, you are still entitled to object to things you find objectionable.</p><p>27. In fact, it is your duty as a citizen of a functioning democracy to do so.</p><p>28. A political leader’s support must be continually earned. Questioning Trump will not bring Obama back, or put Clinton in the White House.</p><p>29. “I like mint ice cream more than chocolate” is an opinion. “There are about 290,000 people in Toledo” is a fact.</p><p>30. Opinions that don’t match yours are not “fake news”.</p><p>31. The existence of “fake news” does not mean that facts no longer exist.</p><p>32. Science is real.</p><p>33. Economics cannot make science not real.</p><p>34. Denying that Trump University was a scam doesn’t make it true.</p><p>35. Saying that your cabinet has the highest IQ ever doesn’t make it true.</p><p>36. Saying that crime is rising doesn’t make it true.</p><p>37. Saying millions of people voted fraudulently doesn’t make it true.</p><p>38. People who lie a lot are unlikely to suddenly stop.</p><p>39. Authoritarians sow confusion to help accumulate and retain power.</p><p>40. Authoritarians seek to divide people against each other to accumulate and retain power. Be skeptical of explanations that blame “them”.</p><p>41. And to distract us.</p><p>42. Democracy happens every day, until we stop practicing it.</p><p>43. Reread the Declaration of Independence once in a while, just for good measure.</p><p>44. There is nothing patriotic about blind obedience to established power.</p><p>45. We may have been born into a functioning democracy, but we are not guaranteed or entitled to one.</p><p>46. This is not normal.</p><p>47. If we treat it as normal for four years, it will become normal.</p><p>48. This must not become normal.</p><p>49. “This too shall pass” is true, but makes no promises about speed.</p><p>50. Running — to a safely “blue” state, or to Canada, or to ignorance and distraction — is an exercise of great privilege that most don’t have.</p><p>51. The world will generally better if people stay and fight.</p><p>52. The good in this country comes from its people, and the power its people have over its government.</p><p>53. While we resist attacks on that good, we must continue to love, and learn, and make art, and dance, and have babies, and grow old, and solve problems, and plant trees, and eat, and sit around watching the sun go down.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3afc37b8c43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Personal Lies of the PEOTUS]]></title>
            <link>https://medium.com/@jrheling/the-personal-lies-of-the-peotus-785032824cac?source=rss-f32c9b464339------2</link>
            <guid isPermaLink="false">https://medium.com/p/785032824cac</guid>
            <category><![CDATA[2016-election]]></category>
            <category><![CDATA[lies]]></category>
            <category><![CDATA[donald-trump]]></category>
            <category><![CDATA[politics]]></category>
            <dc:creator><![CDATA[Josh Heling]]></dc:creator>
            <pubDate>Sun, 15 Jan 2017 16:45:06 GMT</pubDate>
            <atom:updated>2017-01-15T16:45:06.384Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s hard to focus energy and attention on forcing accountability for basic things like personal honesty when so many bigger issues are constantly swirling around. But just as we prioritize developing these basic character traits in our children, we must demand them from those holding our political power.</p><p>A certain set of Trump’s lies and deceptions fit a trend. He was going to <a href="http://www.nationalmemo.com/showusyourtaxes-heres-every-time-donald-trump-has-said-he-would-release-his-tax-returns/">release his tax returns</a> (until <a href="http://www.cnbc.com/2017/01/11/transcript-of-president-elect-donald-j-trumps-news-conference.html">he wasn’t</a>). He was going to <a href="http://www.reuters.com/article/us-usa-trump-idUSKBN13P1DM">separate himself from his business interests</a> (until <a href="https://www.theatlantic.com/politics/archive/2017/01/trump-conflicts-of-interest-business-organization/512861/">he wasn’t</a>). And most recently, he was going to <a href="http://thehill.com/homenews/administration/314368-trump-to-visit-national-african-american-museum-on-mlk-day-report">visit the National Museum of African American History</a>. And <a href="http://thehill.com/homenews/campaign/314385-trump-no-longer-expected-to-visit-national-african-american-museum-on-mlk">now he isn’t</a>.</p><p>A theme connecting these broken promises is that <em>they are personal in nature</em>. They are about him. They depend on no one else. And the making of the to-be-broken promise helps him directly — he gains some relief from the pressure, criticism, or expectation he’s facing. He gets a news cycle. He gives his supporters or those still “giving him a chance” space in which they can reassure themselves of his basic human decency. And then the subsequent change of plans that turns his promise into a lie goes relatively quietly into the night (or, sometimes, loudly into the echo chamber populated by those who have already written him off).</p><p>Some would respond that all politicians lie. But there’s a qualitative difference here. “I will release my tax returns if I win the nomination” is a specific assurance meant to relieve the pressure of a legitimate demand and defer it until later. As is “on December 15th, I will unveil plans to fully separate myself from my businesses”. These are different in kind from the sort of aspirational campaign trail statements that we expect a politician to make and then oftentimes fail to make good on. “I will bring jobs back to Springfield” is a policy goal, but the audience hearing it knows that the speaker cannot unilaterally do so. Any reasonable listener hears an implied “I will try to …” prefacing these promises. And the way our system works (for good reason), these things sometimes do not come to pass. The personal flavor of Trump lie, though, is different — it is more like “I will meet you for coffee tomorrow at 8”. When a promise of this form is casually broken, it says a lot about the character of the speaker, their regard and respect for the audience, or both.</p><p>That lack of respect — for us — is perhaps most troubling. This is the behavior pattern of an autocrat. And it connects to the <a href="https://www.youtube.com/watch?v=R58fJ7Eetbg&amp;feature=youtu.be">ethics</a> issue from earlier this week. Some want to see the ethics things as a matter of technical compliance with some bureaucratic rule. But underlying both this pattern of carelessly broken personal promises and his steadfast refusal to separate his interests from ours is the reality that <em>this man has no idea what it means to be a public servant, or at least no concern about acting as one</em>.</p><p>When we evaluate the government service component of a political candidate’s resume, one thing we’re looking for is evidence that the person has proven administrative, organizational, and leadership skills. In this regard, business experience is frequently seen as at least equivalent, and in some cases preferable to, time in government. That might be reasonable. But the other thing we see in that resume entry is an actual investment of personal effort toward the common good.</p><p>Trump’s string of personal lies and refusal to actually separate his personal interests from his presidential power are important reminders that nothing in his past has been about anything other than benefitting Donald J. Trump. And he has not given us any reason to think that this will change come Inauguration Day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785032824cac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>