title: Jest wait for promise to resolve before finding an element
body: <p>This is my sample code of React (the actual code resembles a lot to this but is too long to put here):</p>
  
  <pre><code>class Test extends Component {  
      state = {
          show: false
      }
      render() {
          return (
          &lt;&gt;
          {this.state.show &amp;&amp; &lt;div&gt;Hello&lt;/div&gt;}
          &lt;button
              onClick={() =&gt; {
  
                  //an ajax call to fetch data from server
                  new Promise((resolve) =&gt; resolve(null)).then(() =&gt; {
                  this.setState({show: true})
                  })
              }}
          /&gt;
          &lt;/&gt;
        )
      }
  }
  </code></pre>
  
  <p>The jest test is below:</p>
  
  <pre><code>it('test', () =&gt; {
      const component = mount(&lt; Test /&gt;);
      expect(component.find('div').length).toEqual(0); //passes
  
      component.find('button').prop&lt;Function&gt;('onClick')();
      expect(component.find('div').length).toEqual(1); //unstable response
  })
  </code></pre>
  
  <p>Now the problem I am facing is that when I run this kind of tests where to find a component depends on a promise resolving, the tests are unstable. Some times they pass and sometime the component is not found.</p>
  
  <p>The things that I have tried:</p>
  
  <p>1- Using this sleep function:</p>
  
  <pre><code>const sleep = (milliseconds: number) =&gt; {
    return new Promise&lt;number&gt;(resolve =&gt; setTimeout(resolve, milliseconds));
  };
  </code></pre>
  
  <p>And then use <code>await sleep(1)</code> after triggering a promise</p>
  
  <p>2- Using this flush promises function:</p>
  
  <pre><code>const flushPromises = () =&gt; {
    return new Promise(resolve =&gt; setImmediate(resolve));
  }
  </code></pre>
  
  <p>But I am unable to find the stability I want. The other thing this causes is if there are chained promises, then the test (mostly but not always hence unstable) exits before all the promises are resolved (which obviously cause the tests to fail). I have tried to increase timeout (third argument of <code>it</code> ) and use done callback, but of no use.</p>
  
  <p>Can someone explain what am I doing wrong here and how the promise resolving works in <code>jest</code> test environment.</p>