title: Flushing a Promise queue?
body: <p>While writing tests using Jest, an asynchronous mocked Axios request was causing a <code>setState()</code> call after a component was mounted. This resulted in console output during the test run.</p>
  
  <pre><code>it('renders without crashing', () =&gt; {
    const mockAxios = new MockAdapter(axios);
  
    mockAxios.onGet(logsURL).reply(200, [...axios_logs_simple]);
  
    const div = document.createElement('div');
    ReactDOM.render(&lt;Logs /&gt;, div);
    ReactDOM.unmountComponentAtNode(div);
  });
  </code></pre>
  
  <p>And in the <code>&lt;Logs&gt;</code> component:</p>
  
  <pre><code>componentDidMount() {
    axios.get(apiURL).then(response =&gt; {
      this.setState({data: response.data});
    });
  }
  </code></pre>
  
  <p>I found a <a href="https://bluz71.github.io/2018/01/02/mock-axios-in-react-jest_enzyme-tests.html" rel="nofollow noreferrer">blog post</a> showing a solution, but I don't understand how it does anything useful:</p>
  
  <pre><code>it('renders without crashing', async () =&gt; { //&lt;-- async added here
    const mockAxios = new MockAdapter(axios);
  
    mockAxios.onGet(logsURL).reply(200, [...axios_logs_simple]);
  
    const div = document.createElement('div');
    ReactDOM.render(&lt;Logs /&gt;, div);
    await flushPromises(); //&lt;-- and this line here.
    ReactDOM.unmountComponentAtNode(div);
  });
  
  const flushPromises = () =&gt; new Promise(resolve =&gt; setImmediate(resolve));
  </code></pre>
  
  <p>As I understand it, it creates a new promise that resolves immediately. How can that guarantee other asynchronous code will resolve?</p>
  
  <p>Now, it solved the issue. There are no more console messages during the test run. The test still passes (it's not a very good one). But this just seems like I just landed on the other side of a race condition, rather than preventing the race condition in the first place.</p>