title: How to test redux-thunk middleware async functions?
body: <p>I'm trying to test my asyn <strong>thunk middleware</strong> function using <strong>mocha, chai and sinon</strong> (my first time!).</p>
  
  <p>Please consider my files:</p>
  
  <p>ayncActionCreators.js</p>
  
  <pre><code>export const fetchCurrentUser = () =&gt; {
     return (dispatch) =&gt; {
        setTimeout(dispatch, 100);
     }
  };
  </code></pre>
  
  <p>ayncActionCreators.spec.js</p>
  
  <pre><code>//...
  it('Should work', () =&gt; {
     const dispatch = sinon.spy();
     const action = fetchCurrentUser();
  
     action(dispatch);
  
     expect(dispatch.called).to.be.true;
  });
  </code></pre>
  
  <p>I did not yet implement the fetchCurrentUser function - just assumed it will take some "server" time and then it will call 'dispatch()'.</p>
  
  <p>The spec fails, due to the async flow. If I add a setTimeout of 101 ms before the expect - it passes.</p>
  
  <p>My code will use some DB API that returns promise, so the async function will eventually look like:</p>
  
  <pre><code>//...
  return (dispatch) =&gt; {
     return dbAPI.fetchUser().then(dispatch(....));
  }
  </code></pre>
  
  <p>So I tried to require dbAPI and create a sinon.stub().returns(Promise.resolve()) inside the test and it didn't work as well (I thought that since the stub returns a resolved promise - the async function will act like a synchronous function).</p>
  
  <p>Any ideas how should I test async functions like that?</p>
  
  <p>Thank,
  Amit. </p>