Automating Fixture Instantiation in Mocha using Async

by Jason on January 31, 2012

My latest Node.JS project has been entirely test-driven and I always strive to write very simple & concise tests. Convoluted code in a test will be far less likely to be maintained.

So when test driving my latest model, I found myself using hundreds of lines of code just to instantiate models using pre-built fixtures in the before function. Not ideal.

I much prefer this type of code:


var my_model_fixtures = require(app.root+'/spec/models/fixtures/my_model_fixtures.js');

describe('My Model', function() {  
  before(function(done) {    
    this.my_models = new Array;
    var that=this;
    
    async.map(['fixture1', 'fixture2'],
      function(my_fixture, iterator_callback) {
        var my_model = new MyModel(my_model_fixtures[my_fixture]);
        my_model.save(function(err,data){
          if(!err) {
            iterator_callback(null, my_model);
          } else {
            iterator_callback(data, null);
          }
        });
      },
      function(err,results){
        if(err) {
          console.log("Error instantiating fixtures: "+err);
        }
        done(err);
      });
  });  
});