title: How to code coverage a promise inside functions while unit testing using Jest
body: <p>How to code cover then and catch function of a promise inside a function while unit testing using jest? Please see code below.</p>
  
  <p>Service.js</p>
  
  <pre><code>export const userLogin = data =&gt; {
    return AjaxService.post(
      "http://localhost/3000/signin", data
    ).then(
      res =&gt; {
        return res.data;
      },
      error =&gt; {
        return error.response.data;
      }
    );
  };
  </code></pre>
  
  <p>AjaxService.js</p>
  
  <pre><code>export const AjaxService = {
    post: (url, data, headers) =&gt; {
      return axios({
        method: "POST",
        url: url,
        headers: headers || { "content-type": "application/json" },
        data: data
      });
    }
  </code></pre>
  
  <p>}</p>
  
  <p>Example.js</p>
  
  <pre><code>class Login extends Component {
  
    handleSubmit = (event) =&gt; {
      if (this.props.handleSubmit) this.props.handleSubmit(); 
      this.setState({isLoggedIn: true})
      userLogin().then((res) =&gt; {
       // when promise resolve
       var response = res;
      }, (err) =&gt; {
        // when promise reject  
        var error = err;
      })
    }
    render() {
     return (
      &lt;form id="login-form" onSubmit={(e) =&gt; this.handleSubmit(e)} &gt;
       &lt;input type="username" /&gt;
       &lt;input type="password" /&gt;
       &lt;button type="submit"&gt;Login&lt;/button&gt;
      &lt;/form&gt;
     )
    }
  
  }
  </code></pre>
  
  <p>Example.test.js</p>
  
  <pre><code>it("test login form submit ", () =&gt; {
      wrapper = shallow(&lt;Login /&gt;);
      let instance = wrapper.instance(); // get class instance
      instance.handleSubmit(); // will trigger component method
      let actualVal = wrapper.state().isLoggedIn; // get state key value
      expect(true).to.eql(actualVal);
    });
  </code></pre>
  
  <p>After generating coverage report using <code>--coverage</code> in Jest</p>
  
  <p><a href="https://i.stack.imgur.com/g9eDL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g9eDL.png" alt="enter image description here"></a></p>
  
  <p>We can see that the code inside promise success and error function doesn't get covered as part of unit testing. So please help cover this. Thanks.</p>