title: Running node.js tests against test data in a MongoDB database
body: <p>I'm trying to set up a script to execute tests for my node.js program, which uses MongoDB. The idea is that I want to have a script I can run that:</p>
  
  <ol>
  <li>Starts the MongoDB process, forked as a daemon</li>
  <li>Pre populates the database with some test data</li>
  <li>Starts my node server with forever, so it runs as a daemon</li>
  <li>Run my tests</li>
  <li>Drop the test data from the database</li>
  </ol>
  
  <p>I have a crude script that performs all these steps. My problem is that MongoDB takes a variable amount of time to set up, which results in <code>sleep</code> calls in my script. Consequently it only works occasionally.</p>
  
  <blockquote>
  <pre><code># the directory of this script
  DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &amp;&amp; pwd )"
  
  # launch mongodb.
  $DIR/../../db/mongod --fork --logpath ./logs/mongodb.log --logappend --dbpath ./testdb/ --quiet 
  
  # takes a bit of time for the database to get set up, 
  # and since we make it a daemon process we cant run the tests immediately
  sleep 1
  
  # avoid EADDRINUSE errors because existing node servers are up.
  killall node &amp;&gt; /dev/null
  
  # start up our node server using a test database.
  forever start $DIR/../main.js --dbname=testdb --logpath=test/logs/testlog.log
  
  # takes a bit of time for node to get set up, 
  # and since we make it a daemon process we cant run the tests immediately
  sleep 1
  
  # run any database setup code (inject data for testing)
  $DIR/../../db/mongo 127.0.0.1:27017/testdb $DIR/setup.js --quiet
  
  # actually run the tests
  node $DIR/tests.js
  
  # kill the servers (this could be a little less heavy handed...)
  killall node &amp;&gt; /dev/null
  killall forever &amp;&gt; /dev/null
  
  # finally tear down the database (drop anything we've added to the test db)
  $DIR/../../db/mongo 127.0.0.1:27017/testdb $DIR/teardown.js --quiet
  
  # and then shut mogodb down
  kill -2 `ps ax | grep mongod | grep -v grep | awk '{print $1}'`
  </code></pre>
  </blockquote>
  
  <p>What is the best way to go about what I'm trying to do? Am I going down a rabbit hole here, or am I missing something in the MongoDB docs?</p>