<?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 Manas Tunga on Medium]]></title>
        <description><![CDATA[Stories by Manas Tunga on Medium]]></description>
        <link>https://medium.com/@manastunga?source=rss-5c7c1864d599------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RYWU_F4Qr-dJkP78.jpeg</url>
            <title>Stories by Manas Tunga on Medium</title>
            <link>https://medium.com/@manastunga?source=rss-5c7c1864d599------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:10:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manastunga/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[Unit testing api calls in React , Enzyme and Jest]]></title>
            <link>https://medium.com/@manastunga/unit-testing-api-calls-in-react-enzyme-and-jest-133b87aaacb4?source=rss-5c7c1864d599------2</link>
            <guid isPermaLink="false">https://medium.com/p/133b87aaacb4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[enzyme-js]]></category>
            <dc:creator><![CDATA[Manas Tunga]]></dc:creator>
            <pubDate>Mon, 17 Dec 2018 18:59:43 GMT</pubDate>
            <atom:updated>2019-01-14T18:56:19.999Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit test api calls in React , Enzyme and Jest</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qp5gIVi0i3CDkTVT" /><figcaption>Photo by <a href="https://unsplash.com/@toddquackenbush?utm_source=medium&amp;utm_medium=referral">Todd Quackenbush</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Unit testing your api calls can be cumbersome to some extent, for simplicity here i am using create-react-app and Enzyme and Jest (no redux or redux-thunk).</p><blockquote>Our application has a single react component &lt;Hello/&gt;and we are going to make api call to get user info at it’s <strong><em>componentDidMount</em> </strong>lifecycle method.</blockquote><blockquote><strong>A</strong>nd display user name in a paragraph, after the success of the api call.</blockquote><blockquote>Until the api call resolved we are going to show a span for loading.</blockquote><p>So our <strong>Hello</strong> component has</p><pre>import React from &quot;react&quot;;</pre><pre>export default class Hello extends React.Component {</pre><pre>    constructor(props) {<br>       super(props);<br>       this.state = {<br>         user: null<br>       }<br>    }</pre><pre>    async componentDidMount() {<br>     try {<br>         const res = await fetch(&quot;http://localhost:3000/user&quot;);<br>         if (res.status &gt;= 400)<br>            throw new Error(&quot;something went wrong&quot;)</pre><pre>         const user = await res.json();<br>         this.setState({ user });<br>      } catch (err) {<br>        console.error(err);<br>      }<br>   }<br></pre><pre>   render() {<br>       return (<br>         &lt;div&gt;<br>           &lt;h2&gt;Welcome to hello&lt;/h2&gt;<br>            <br>            {this.state.user ?<br>            &lt;p className=&quot;user&quot;&gt;user:{this.state.user.userName}&lt;/p&gt;<br>             :<br>             &lt;span className=&quot;spinner&quot;&gt;&lt;/span&gt;}<br>         &lt;/div&gt;<br>      );<br>    }<br>}</pre><p>in above code I am using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">fetch</a> to make ajax call to the api endpoint and I have marked the componentDidMount with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async</a> key word so that we can await till our api call resolved. After the success of api call we convert the json response to javascript user object and call the setState withe user data.</p><h3><strong>Lets write the test for this</strong></h3><p>For the Hello component we are going to write two tests</p><blockquote>Hello component must render a loading span before the success of api call</blockquote><blockquote>Must render a paragraphtag with user name after the success of api call and hide the loading spans.</blockquote><pre>import React from &quot;react&quot;;<br>import { shallow } from &quot;enzyme&quot;;<br>import Hello from &quot;./hello&quot;;</pre><pre>beforeAll(() =&gt; {<br>  global.fetch = jest.fn();<br>  //window<em>.fetch = jest.fn(); if running browser environment<br></em>});</pre><pre>let wrapper;</pre><pre>beforeEach(() =&gt; {<br>   wrapper = shallow(&lt;Hello /&gt;, { disableLifecycleMethods: true });<br>});</pre><pre>afterEach(() =&gt; {<br>   wrapper.unmount();<br>});</pre><pre>it(&quot;must render a loading span before api call success&quot;, () =&gt; {<br>    expect(wrapper.find(&quot;span.spinner&quot;).exists()).toBeTruthy();<br>});</pre><pre>it(&quot;must show the p.user and hide the loading span after api call success&quot;, <br>(done) =&gt; {</pre><pre>//<em> here we are spying on componentDidMount to know that it has been called</em></pre><pre>const spyDidMount = jest.spyOn(Hello.prototype,&quot;componentDidMount&quot;);</pre><pre>fetch.mockImplementation(() =&gt; {<br>   return Promise.resolve({<br>     status: 200,<br>     json: () =&gt; {<br>     return Promise.resolve({<br>        userName: &quot;manas&quot;,<br>        userId: 1<br>      });<br>    }</pre><pre>  });<br>});</pre><pre>const didMount = wrapper.instance().componentDidMount();</pre><pre>// expecting componentDidMount have been called</pre><pre>expect(spyDidMount).toHaveBeenCalled();</pre><pre>didMount.then(() =&gt; {<br>   //<em> updating the wrapper<br>   </em>wrapper.update();</pre><pre>   expect(wrapper.find(&quot;p.user&quot;).text()).toContain(&quot;manas&quot;);<br>   expect(wrapper.find(&quot;spans.loading&quot;).length).toBe(0);</pre><pre>   spyDidMount.mockRestore();<br>   fetch.mockClear();<br>   done();<br>});</pre><pre>});</pre><blockquote>let’s break testing code to meaningful pieces</blockquote><p>Before all tests i am mocking the api call with jest.fn() . It is good practice to mock your api call in unit test, as we are doing unit test not integration test.</p><pre>beforeAll(() =&gt; {<br>  global.fetch = jest.fn();<br>  //window<em>.fetch = jest.fn(); if running browser environment<br></em>});</pre><p>I am creating fetch property in global object by global.fetch = jest.fn() and setting it to a jest mock function to make fetch available in nodejs environment. If you are running your code in <a href="http://codesandbox.io/">codesanbox</a> or <a href="https://jsfiddle.net/">jsfiddle</a> use window.fetch = jest.fn() instead.</p><pre>let wrapper;</pre><pre>beforeEach(() =&gt; {<br>   wrapper = shallow(&lt;Hello /&gt;, { disableLifecycleMethods: true });<br>});</pre><pre>afterEach(() =&gt; {<br>   wrapper.unmount();<br>});</pre><p>Before each test I creating a shallow wrapper of Hello component by using Enzyme’s shallow render method.</p><p>Things to be noted here shallow function is called with a second parameter {disableLifecycleMethods:true}.</p><p>This prevents the shallow render to call react lifecycle events like componentDidMount after the render. As a result componentDidMount will not be called automatically after the shallow render and we can test the existence of loading span before the success call of the api.</p><pre>it(&quot;must render a loading span before api call success&quot;, () =&gt; {<br>    expect(wrapper.find(&quot;span.loading&quot;).length).toBe(1);<br>});</pre><p><strong>lets come to the second test.</strong></p><blockquote>Must render a <em>paragraph</em>tag with user name after the success of api call and hide the loading <em>spans</em></blockquote><pre>const spyDidMount = jest.spyOn(Hello.prototype,&quot;componentDidMount&quot;);</pre><p>In the above code we are spying on the componentDidMount to test componentDidMount has been called.</p><pre>fetch.mockImplementation(() =&gt; {<br>   return Promise.resolve({<br>     status: 200,<br>     json: () =&gt; {<br>     return Promise.resolve({<br>        userName: &quot;manas&quot;,<br>        userId: 1<br>      });<br>    }<br>  });<br>});</pre><p>In the above code we are creating a mock implementation of the fetch call to our api. That resolves to a user object {userName:&quot;manas&quot;,userId:1} .</p><pre>const didMount = wrapper.instance().componentDidMount();</pre><p>Now I am calling the componentDidMount method manually of the wrapper instance object that return a promise as our componentDidMount is a async function.</p><pre>didMount.then(() =&gt; {<br>   //<em> updating the wrapper<br>   </em>wrapper.update();</pre><pre>   expect(wrapper.find(&quot;p.user&quot;).text()).toContain(&quot;manas&quot;);<br>   expect(wrapper.find(&quot;spans.loading&quot;).length).toBe(0);</pre><pre>   spyDidMount.mockRestore();<br>   fetch.mockClear();<br>   done();<br>});</pre><p>As wrapper.instance().componentDidMount() returns a promise we can use it’s then() method to write our tests, before that lets update the wrapper by wrapper.update() as success of api call must have called the setState({user}) and that must have updated the view of the Hello component.</p><pre>expect(wrapper.find(&quot;p.user&quot;).text()).toContain(&quot;manas&quot;);<br>expect(wrapper.find(&quot;spans.loading&quot;).length).toBe(0);</pre><p>Expecting the wrapper must have a paragraph now with manas text inside of it. And expecting span with loading class no more available in the updated view.</p><pre>spyDidMount.mockRestore();<br>fetch.mockClear();</pre><p>Restoring the spy and clearing the mock.</p><p>Last but not the least don’t forget to call the done() this tells the jest we are done with the <a href="https://jestjs.io/docs/en/asynchronous.html">async test</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=133b87aaacb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>