title: How to test async methods in React?
body: <p>Could anyone help me with testing of async / Promise based methods in React components? For example I have following really simple React component (it's only dummy code)</p>
  
  <pre><code>import server from './server';
  
  class Button extends Component {
    async handleClick() {
      if (await canDoSomething()) {
        const result = await calculateIt();
        if (result) {
          // will be mocked in my unit test
          await server.sendResultToServer(result);
          localStorage.setItem('sent', 'true');
        }
        localStorage.setItem('sent', 'false');
      }
      if (localStorage.getItem('sent') === 'true') {
        // do something
      }
    }
  
    render() {
      return &lt;button onClick={this.handleClick}&gt;Click me&lt;/button&gt;;
    }
  }
  </code></pre>
  
  <p>Now in my test I could mock most of the async methods with sinon like so:</p>
  
  <pre><code>it('should do something', async () =&gt; {
    const promise = Promise.resolve();
    sinon.stub(server, 'sendResultToServer', () =&gt; promise);
    const wrapper = shallow(&lt;Button /&gt;);
    wrapper.find(&lt;button /&gt;).simulate('click');
    // this await will be resolved FIRST. Only then
    // await server.sendResultToServer(result); in my code will be resolved
    await promise;
    expect(localStorage.getItem('sent')).to.equal('true');
  })
  </code></pre>
  
  <p>If you first see this code you should think that everything is ok. But unfortunately it's not. In my test I am awaiting the promise <code>await promise;</code> and <strong>after</strong> that I make my expectations. But the implementation code also awaits the promise. So when the promise fulfills in <strong>both</strong> places the expectation runs <strong>before</strong> the code in the implementation runs. In other words: my test runs before the code to test (tested on my machine using Mocha / Chai / Enzyme). What I need is the reversed order.</p>
  
  <p>Does anyone know how to solve that?</p>