title: Nodejs Testing. How to avoid Race Conditions?
body: <p>I am currently writing a game engine in nodejs.</p>
  
  <p>My game has several states. Let's call them StateA, StateB, StateC. The flow of sequence is StateA => StateB => StateC. </p>
  
  <p>I would like to test the state of my engine at the end of each state. I currently have this structure: </p>
  
  <pre><code>function attachEventListeners = function(instance) {
    instance.on('START_STATE_A', stateA);
    instance.on('START_STATE_B', stateB);
    instance.on('START_STATE_C', stateC);
  }
  
  var stateACallBack = function() {};
  var stateBCallBack = function() {};
  var stateCCallBack = function() {};
  
  function stateA() { 
    // Do something...
    stateACallBack();
    setTimeout(function() { this.emit('START_STATE_B'); }, 3000)
  }
  
  function stateB() { 
    // Do something...
    stateBCallBack();
    setTimeout(function() { this.emit('START_STATE_C'); }, 3000)
  }
  
  function stateC() { 
    // Do something...
    stateCCallBack();
    setTimeout(function() { this.emit('START_STATE_A'); }, 3000)
  }
  </code></pre>
  
  <p>So my current approach involves having my test cases override stateXCallback and executing the testing logic in those functions.</p>
  
  <p>However, I am seeing a race condition where stateB is fired <strong>before</strong> stateACallBack has finished executing. As a result, stateACallback is seeing states that should be evaluated by stateBCallback instead.</p>
  
  <p>I tried injecting a delay time between the states, however, this introduces additional race condition bugs in my codebase. </p>
  
  <p>Can someone please enlighten me a better approach to this problem? </p>