<?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 Andre Calvo on Medium]]></title>
        <description><![CDATA[Stories by Andre Calvo on Medium]]></description>
        <link>https://medium.com/@AndreCalvo?source=rss-a37169b39c3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZGvy6743YnfFYERo8-heXQ.jpeg</url>
            <title>Stories by Andre Calvo on Medium</title>
            <link>https://medium.com/@AndreCalvo?source=rss-a37169b39c3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:54:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AndreCalvo/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[Testing custom react hooks that use fetch (or other async functions)]]></title>
            <link>https://medium.com/@AndreCalvo/testing-custom-react-hooks-that-use-fetch-or-other-async-functions-5fb128d07f53?source=rss-a37169b39c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fb128d07f53</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andre Calvo]]></dc:creator>
            <pubDate>Thu, 27 Jun 2019 18:55:33 GMT</pubDate>
            <atom:updated>2019-08-23T09:20:39.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6C4nSvy2Woe0m7bWEn4BA.png" /></figure><h3>Testing custom react hooks that use fetch (or other async behaviour)</h3><h3>The custom hook</h3><p>There are a few <em>gotchas </em>when testing custom hooks that have async behaviour, such as the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">fetch</a> API. At the time of writing you have to use the alpha version (<a href="https://github.com/facebook/react/releases/tag/v16.9.0-alpha.0">v16.9.0-alpha.0</a>) of <a href="https://github.com/facebook/react">react</a>, <a href="https://github.com/facebook/react/tree/master/packages/react-dom">react-dom</a> and <a href="https://github.com/facebook/react/tree/master/packages/react-test-renderer">react-test-renderer</a>. Hopefully in the not too distant future this will be part of the stable react codebase.</p><p><strong>Update: 16.9.0 is now stable, don’t use the alpha as mentioned above.</strong></p><p>If you are getting errors such as…</p><pre>Warning: An update to TestHook inside a test was not wrapped in act(...).</pre><pre>When testing, code that causes React state updates should be wrapped into act(...):</pre><pre>act(() =&gt; {<br>      /* fire events that update state */<br>    });<br>    /* assert on the output */</pre><pre>This ensures that you&#39;re testing the behavior the user would see in the browser. Learn more at <a href="https://fb.me/react-wrap-tests-with-act">https://fb.me/react-wrap-tests-with-act</a><br>        in TestHook<br>        in Suspense</pre><p>…this may help.</p><p>Here’s a simple example of a custom hook I wrote that calls an API using fetch:</p><p><a href="https://gist.github.com/andrecalvo/b4fa0390efec6212cd464111e7f6272a#file-usedataapi-jsx">Gist link</a></p><pre>import { useEffect, useState, useRef } from &quot;react&quot;;<br><br>export const useDataApi = () =&gt; {<br>  const firstUpdate = useRef(true);<br>  const [error, setError] = useState(false);<br>  const [apiUrl, setApiUrl] = useState(&quot;&quot;);<br>  const [data, setData] = useState(null);<br><br>  useEffect(<br>    () =&gt; {<br>      if (!firstUpdate.current) {<br>        fetch(apiUrl)<br>          .then(response =&gt; response.json())<br>          .then(response =&gt; {<br>            setData(response);<br>          })<br>          .catch(error =&gt; {<br>            setError(true);<br>          });<br>      }<br>      firstUpdate.current = false;<br>    },<br>    [apiUrl]<br>  );<br>  return { data, error, callApi: setApiUrl };<br>};</pre><p>I’m using useRef(true) to make sure it doesn’t make a call on it’s first render and useState to update the error/data state which is then returned for use by other components. useEffect is making sure the API call is only triggered when the apiUrl has been updated via setApiUrl.</p><p>It can be imported and used within another component by calling callApi with a string, like so:</p><pre>...<br>const { data, error, callApi } = useDataApi();<br>...<br>function handleClick(type, filterValue) {   <br>  callApi(&quot;your/data/endpoint/here.com&quot;);<br>}<br>...</pre><pre>return(  <br>  ...<br>  {data.whateverIsReturned}<br>  ...<br>)</pre><p>You can also use the error variables to conditionally show error messages.</p><h3>Testing</h3><p>My examples are using jest but you will need a few more libraries to get this to work.</p><ul><li><a href="https://reactjs.org/docs/test-renderer.html">react-test-renderer</a> (make sure this is the <a href="https://github.com/facebook/react/releases/tag/v16.9.0-alpha.0">v16.9.0-alpha.0</a> version until 16.9.0 is released).</li><li><a href="http://www.wheresrhys.co.uk/fetch-mock/">fetch-mock</a> to intercept my network requests for testing purposes. If you’re using axios checkout <a href="https://github.com/knee-cola/jest-mock-axios#readme">jest-mock-axios</a>.</li><li><a href="https://github.com/testing-library/react-hooks-testing-library#readme">@testing-library/react-hooks</a> provides utilities to make testing hooks easier.</li><li><a href="https://github.com/whatwg/fetch">whatwg-fetch</a> allows us to use fetch in the node environment, like we would in the browser.</li></ul><h3>Boilerplate</h3><p>Your test file, without any tests should begin like this:</p><p><a href="https://gist.github.com/andrecalvo/b4fa0390efec6212cd464111e7f6272a#file-usedataapi-boilerplate-test-jsx">Gist link</a></p><pre>import React from &quot;react&quot;;<br>import { useDataApi } from &quot;path/to/hoo/useDataApi.jsx&quot;;<br>import &quot;whatwg-fetch&quot;;<br>import { renderHook } from &quot;@testing-library/react-hooks&quot;;<br>import fetchMock from &quot;fetch-mock&quot;;<br>import { act } from &quot;react-test-renderer&quot;;<br><br>describe(&quot;useDataApi&quot;, () =&gt; {<br>  beforeAll(() =&gt; {<br>    global.fetch = fetch;<br>  });<br>  afterAll(() =&gt; {<br>    fetchMock.restore();<br>  });<br>});</pre><p>In our beforeAll and afterAll we set global.fetch to a polyfilled version of fetch so it can be used by your jest tests, we then restore this after the tests have finished.</p><h3>The tests</h3><p>There are a few things to remember.</p><ul><li>Use act to wrap any behaviours which update the state of the behaviour, in our case it’s calling callApi but this could also be the clicking of a button for example.</li><li>As fetch is async, we must use await act(async () =&gt; {...})</li></ul><h3>Testing a successful response</h3><p><a href="https://gist.github.com/andrecalvo/b4fa0390efec6212cd464111e7f6272a#file-usedataapi-success-test-jsx">Gist link</a></p><pre>import React from &quot;react&quot;;<br>import { useDataApi } from &quot;path/to/hoo/useDataApi.jsx&quot;;<br>import &quot;whatwg-fetch&quot;;<br>import { renderHook } from &quot;@testing-library/react-hooks&quot;;<br>import fetchMock from &quot;fetch-mock&quot;;<br>import { act } from &quot;react-test-renderer&quot;;<br><br>describe(&quot;useDataApi&quot;, () =&gt; {<br>  beforeAll(() =&gt; {<br>    global.fetch = fetch;<br>  });<br>  afterAll(() =&gt; {<br>    fetchMock.restore();<br>  });<br><br>  it(&quot;should return data with a successful request&quot;, async () =&gt; {<br>    const { result } = renderHook(() =&gt; useDataApi());</pre><pre>    fetchMock.mock(&quot;test.com&quot;, {<br>      returnedData: &quot;foo&quot;<br>    });</pre><pre>    await act(async () =&gt; {<br>      result.current.callApi(&quot;test.com&quot;);<br>    });<br><br>    expect(result.current.data).toBe({<br>      returnedData: &quot;foo&quot;<br>    });<br>  });<br>});</pre><h3>Testing an erroneous response</h3><p><a href="https://gist.github.com/andrecalvo/b4fa0390efec6212cd464111e7f6272a#file-usedataapi-error-test-jsx">Gist link</a></p><pre>import React from &quot;react&quot;;<br>import { useDataApi } from &quot;path/to/hoo/useDataApi.jsx&quot;;<br>import &quot;whatwg-fetch&quot;;<br>import { renderHook } from &quot;@testing-library/react-hooks&quot;;<br>import fetchMock from &quot;fetch-mock&quot;;<br>import { act } from &quot;react-test-renderer&quot;;<br><br>describe(&quot;useDataApi&quot;, () =&gt; {<br>  beforeAll(() =&gt; {<br>    global.fetch = fetch;<br>  });<br>  afterAll(() =&gt; {<br>    fetchMock.restore();<br>  });<br><br>  it(&quot;should return error as true if api error&quot;, async () =&gt; {<br>    const { result } = renderHook(() =&gt; useDataApi());<br><br>    fetchMock.mock(&quot;test.com&quot;, 500);<br><br>    await act(async () =&gt; {<br>      result.current.callApi(&quot;test.com&quot;);<br>    });<br><br>    expect(result.current.data).toBe(null);<br>    expect(result.current.error).toBe(true);<br>  });<br>});</pre><p>All Gists can be found <a href="https://gist.github.com/andrecalvo/b4fa0390efec6212cd464111e7f6272a">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fb128d07f53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a GraphQL api with Apollo, Node, Express, Sequelize, and Postgres.]]></title>
            <link>https://medium.com/@AndreCalvo/creating-a-graphql-api-with-apollo-node-express-sequelize-and-postgres-a26f3a8966ac?source=rss-a37169b39c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a26f3a8966ac</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Andre Calvo]]></dc:creator>
            <pubDate>Fri, 14 Dec 2018 15:03:00 GMT</pubDate>
            <atom:updated>2019-09-16T22:52:02.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a GraphQL API with Apollo, Node, Express, Sequelize, and Postgres.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*wOO_h3bXKqANfe8s.png" /></figure><p>TL;DR - <a href="https://github.com/andrecalvo/GraphQL-Apollo-Node-Express-Apollo-Postgres-Sequelize-starter">https://github.com/andrecalvo/GraphQL-Apollo-Node-Express-Apollo-Postgres-Sequelize-starter</a></p><p>I recently started a project where I wanted to use Apollo GraphQL and Node/Express to create an api. Although the individual documentation for these libs are great, when trying to use them together I looked to blogs for help.</p><p>There were a handful of articles to read (some of which helped me create this) but I struggled to find a “simple” example with minimal dependencies and workarounds.</p><p><em>It’s probably worth pointing out now that the intention of this article is to briefly explain some of the code to let you dig around </em><a href="https://github.com/andrecalvo/GraphQL-Apollo-Node-Express-Apollo-Postgres-Sequelize-starter"><em>the repo</em></a><em> yourself.</em></p><p>This project uses the following:<br> - Postgres<br> - Node with an Express server<br> - Apollo GraphQL<br> - Sequelize</p><h3>The models and data</h3><p>If you follow the readme you should end up with a data set with 3 categories and 3 locations (this is generated via the migrations and seeds, you can find out more about this <a href="http://docs.sequelizejs.com/manual/installation/getting-started.html">here</a>).</p><p>There is a many-to-many relationship between tables. For example, a location can have many categories and vice versa. You can see how this is achieved with Sequelize in the models directory.</p><pre>&quot;use strict&quot;;<br>module.exports = (sequelize, DataTypes) =&gt; {<br>  var Categories = sequelize.define(&quot;Categories&quot;, {<br>    name: DataTypes.STRING,<br>    updatedAt: DataTypes.INTEGER,<br>    createdAt: DataTypes.INTEGER,<br>    id: {<br>      type: DataTypes.INTEGER,<br>      primaryKey: true,<br>      allowNull: false,<br>      autoIncrement: true<br>    }<br>  });<br>  Categories.associate = function(models) {<br>    Categories.belongsToMany(models.Locations, {<br>      through: &quot;CategoriesLocations&quot;,<br>      foreignKey: &quot;categoryId&quot;<br>    });<br>  };<br>  return Categories;<br>};</pre><p>Here’s the example categories model. As well as the basics of setting the property data types you can also see that we set the association using the name of the join table and foreign key. As this is a many-to-many relationship so we have a similar association in the locations model. Sequelize has various different features so I suggest looking at their documentation if you have a different use case.</p><h3>Resolvers</h3><p>Creating an Apollo server requires you to pass in resolvers. Resolvers essentially hold the logic of how your queries/mutations map to the appropriate data.</p><p>In the case of this project we have a categories resolver which uses Sequelize to query the database and return all of the categories.</p><pre>categories: (parent, args, { db }, info) =&gt; {<br>  return db.Categories.findAll();<br>}</pre><p>The rest of the resolvers can be found in the resolvers directory. There is a more complicated example for locations which shows how you can pass arguments from your query.</p><h3>Queries/Mutations</h3><p>After running your server you should be able to access the GraphQL playground on <a href="http://localhost:4000/graphql">http://localhost:4000/graphql</a>.</p><p>The api exposes a few simple queries. You can list all the categories and the locations. You can also pass in an argument to the locations query and only show locations based on their ID.</p><p>To find them all just take out the argument `(categoryId:1)`</p><pre>query {<br>  locations(categoryId:1){<br>    name,<br>    id<br>  }<br>}</pre><p>To find all categories:</p><pre>query {<br>  categories{<br>    name,<br>    id<br>  }<br>}</pre><p>There is also a mutation which allows you to add a category.</p><pre>mutation {<br>  addCategory(categoryName: &quot;Night life&quot;) {<br>    name<br>  }<br>}</pre><p>The schema directory contains all the code for this. I followed a <a href="https://blog.apollographql.com/modularizing-your-graphql-schema-code-d7f71d5ed5f2">great article</a> which showed a nice way modularise your types, queries and mutations.</p><p>There is more to look at in this project but hopefully it’s brief and vanilla enough to be self-explanatory. Feel free to get in contact if you have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a26f3a8966ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React component testing… method calls, mocking components and faking time.]]></title>
            <link>https://medium.com/@AndreCalvo/react-component-testing-mocking-method-calls-components-and-time-d780d45e4cd5?source=rss-a37169b39c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d780d45e4cd5</guid>
            <category><![CDATA[rewirejs]]></category>
            <category><![CDATA[sinonjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[enzyme]]></category>
            <dc:creator><![CDATA[Andre Calvo]]></dc:creator>
            <pubDate>Sun, 16 Apr 2017 22:06:27 GMT</pubDate>
            <atom:updated>2018-02-05T23:16:42.624Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="http://15gifts.com/">15gifts</a> we’ve been busy rebuilding the front-end of our decision engine with React and Redux.</p><p>When writing our unit tests it wasn’t immediately clear how to:</p><ul><li>Test method calls on component classes.</li><li>Mock components within other components.</li><li>Test state changes after a setTimeout().</li></ul><p>Here are some snippets that show the techniques we’ve found useful to complete the above… I’m using <a href="https://github.com/mochajs/mocha">Mocha</a>, <a href="https://github.com/chaijs/chai">Chai</a>, <a href="https://github.com/airbnb/enzyme">Enzyme</a>, <a href="https://github.com/sinonjs/sinon">Sinon</a> and <a href="https://github.com/speedskater/babel-plugin-rewire">Rewire</a> in the examples.</p><h3>Testing method calls on component classes</h3><p>If you’re using Redux, a lot of the time your component will call actions on events like ‘click’. In this component when the user clicks a div we would like to call a handleClick method instead.</p><pre>class Button extends Component {<br>  render() {<br>    return (<br>      &lt;div onClick={()=&gt;this.handleClick()}&gt;Click me!&lt;/div&gt;<br>    )<br>  }</pre><pre>  handleClick() {<br>   alert(&#39;Clicked&#39;)<br>  }<br>}</pre><p>To test this functionality we will be using Sinon to replace the handleClick() method on our component with a “spy”..</p><blockquote>A test spy is a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls. There are two types of spies: Some are anonymous functions, while others wrap methods that already exist in the system under test.</blockquote><blockquote><a href="http://sinonjs.org/releases/v2.1.0/spies/">http://sinonjs.org/releases/v2.1.0/spies/</a></blockquote><pre>import React from &#39;react&#39;<br>import { shallow } from &#39;enzyme&#39;<br>import { expect } from &#39;chai&#39;<br>import sinon from &#39;sinon&#39;<br>import Button from &#39;../Button&#39;</pre><pre>describe(&#39;Button component&#39;, () =&gt; {<br>  it(&#39;should call handleClick() when clicked&#39;, () =&gt; {<br>    const spy = sinon.spy(Button.prototype, &#39;handleClick&#39;)<br>    const wrapper = shallow(&lt;Button /&gt;)</pre><pre>    wrapper.find(&#39;div&#39;).simulate(&#39;click&#39;)      <br>    expect(spy.calledOnce).to.equal(true)<br>  })<br>})</pre><p>Above you can see that we create a spy and assign it to a method the component using the component&#39;sprototype. Enzyme’s wrapped version of our component allows us to easily simulate a click event. The spy’s calledOnce property will now equal true allowing us to assert that the div was clicked.</p><p>Sinon lets us do some other cool things with spies like testing if a function was called with certain arguments. Their <a href="http://sinonjs.org/releases/v2.1.0/spies/">documentation</a> is pretty good so check it out if you have some more complicated functions to test.</p><h3>Mocking a component</h3><p>React allows us to render components within other components..</p><pre>import Book from &#39;../Book&#39;</pre><pre>class Library extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;        <br>      &lt;p&gt;An example of a component containing a component&lt;/p&gt;           <br>      &lt;Book<br>        author={&#39;Some guy&#39;}<br>        title={&#39;A book about something&#39;}<br>        genre={&#39;Horror&#39;} /&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><p>Lets imagine that this Library component is the smallest Library in the World and renders a single Book. When we test theLibrary component we don’t want to also test the Book component and its functionality, we can leave that for another test. All we want to do is test that Library contains a Book.</p><p>To do this we can use <a href="https://github.com/speedskater/babel-plugin-rewire">Rewire</a>, a Babel plugin that allows you to mock components. After installing Rewire via npm you can add the plugin to your .babelrc file like so…</p><pre>...<br>&quot;plugins&quot;: [&quot;rewire&quot;],<br>...</pre><p>And then to mock the component in your test it’s as easy as…</p><pre>import React from &#39;react&#39;<br>import { shallow } from &#39;enzyme&#39;<br>import { expect } from &#39;chai&#39;<br>import Library from &#39;../Library&#39;</pre><pre>const FakeBook = React.createClass({<br>  render: () =&gt; &lt;div&gt;Fake Book&lt;/div&gt;,<br>})</pre><pre>Library.__Rewire__(&#39;Book&#39;, FakeBook)</pre><pre>describe(&#39;Library component&#39;, () =&gt; {<br>  it(&#39;should contain 1 Book&#39;, () =&gt; {<br>    const wrapper = shallow(&lt;Library /&gt;)<br>    expect(wrapper.find(FakeBook)).to.have.length(1)<br>  })<br>})</pre><p>Rewire replaces the Book component withFakeBook which simply renders a div and you don’t have to worry about any props or logic that happens in the Book component.</p><h3>Faking time</h3><p>This is a contrived example but it represents how we might want to change state after a given amount of time using setTimeout(). After 2 seconds the text should change from ‘Running’ to ‘Done’.</p><pre>class Timer extends React.Component {<br>  constructor (props) {<br>    super(props)<br>    this.state = {timerStatus: &#39;Running&#39;}<br>    <br>    setTimeout( () =&gt; {<br>      this.setState({timerStatus: &#39;Done&#39;})<br>    }, 2000)<br>  }</pre><pre>  render() {<br>    return &lt;div&gt;<br>      &lt;h1&gt;{this.state.timerStatus}&lt;/h1&gt;<br>    &lt;/div&gt;<br>  }<br>}</pre><p>Sinon offers a really cool API to fake time…</p><blockquote>var clock = sinon.useFakeTimers();</blockquote><blockquote>Causes Sinon to replace the global setTimeout, clearTimeout, setInterval, clearInterval and Date with a custom implementation which is bound to the returned clock object.</blockquote><blockquote><a href="http://sinonjs.org/releases/v2.1.0/fake-timers/">http://sinonjs.org/releases/v2.1.0/fake-timers/</a></blockquote><p>After this we call clock.tick(2000) to fake a 2 seconds in our component.</p><pre>import React from &#39;react&#39;<br>import { shallow } from &#39;enzyme&#39;<br>import { expect } from &#39;chai&#39;<br>import sinon from &#39;sinon&#39;<br>import Timer from &#39;../Timer&#39;</pre><pre>describe(&#39;Timer component&#39;, () =&gt; {<br>  it(&#39;should render &quot;done&quot; after 2 seconds&#39;, () =&gt; {<br>    const wrapper = shallow(&lt;Timer /&gt;)<br>    clock = sinon.useFakeTimers()<br>    clock.tick(2000)<br>    expect(wrapper.find(&#39;h1&#39;)).to.contain.(&#39;Done&#39;)<br>  })<br>})</pre><p>We can then assert that the component contains ‘Done’ as expected.</p><p>These examples may be simplified for the purpose of demonstration but hopefully they give some insight in testing some common functionality in React.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d780d45e4cd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>