Search code examples
javascripttestingmeteorjasminemeteor-velocity

Jasmine - Running beforeAll blocks in series


Before testing a certain feature of my Meteor application with Jasmine I have to prepare different things for the tests. Therefore I use beforeAll blocks.

  1. Reset the database
  2. Create a lecture in the database
  3. Create a question in the database
  4. Go to the page of the just created lecture
  5. Wait for the Router to finish routing

These asynchronous tasks have to run in series. I can not first go to the lecture page and then create it in the database. Sadly beforeAll blocks in Jasmine will not automatically run in series.

This is my current code:

  beforeAll(function(done) {
    Fixtures.clearDB(done);
  });

  beforeAll(function(done) {
    Fixtures.createLecture({}, function(error, result) {
      lectureCode = result;
      done();
    });
  });

  beforeAll(function(done) {
    Fixtures.createQuestion({}, done);
  });

  beforeAll(function(done) {
    Router.go('lecturePage', {lectureCode: lectureCode});
    Tracker.afterFlush(done);
  });

  beforeAll(waitForRouter);
  
  it("....", function() {
    ...
  });

How can I write this code in Jasmine in a pretty style without going into callback hell?

The Source Code of the entire application is open source and can be found on GitHub

Thank you very much in advance, Max


Solution

  • Here you are:

    beforeAll(function(done) {
        async.series([
        function(callback) {
            Fixtures.clearDB(callback)
        },
        function(callback) {
            Fixtures.createLecture({}, function(error, result) {
                lectureCode = result;
                callback();
            });
        },
        function(callback) {
             Fixtures.createQuestion({}, callback);
        },
        function(callback) {
            Router.go('lecturePage', {lectureCode: lectureCode});
            Tracker.afterFlush(callback);
        }],function(err, results){ // callback called when all tasks are done
            done();
        });
    }
    

    I haven't tested it but I hope you get an idea. You need to create list of functions, each of them will be provided with callback function that you need to call to make next function run. After that final callback is called where we can call done() to tell jasmine that we're done. Hope this helps.