Adam Zerner
Adam Zerner

Reputation: 19278

Jasmine's afterEach seems to be running before the beforeEach in testing my REST API

Code:

describe('GET /:id', function() {
  var post;

  beforeEach(function() {
    var options = {
      uri: base_url,
      method: 'POST',
      json: {
        title: 'one'
      }
    };
    request(options, function(err, response, body) {
      console.log('body: ', body);
      if (err) console.log('ERROR IN THE SET UP.');
      else { post = body; }
    });  
  });

  afterEach(function() {
    console.log('in afterEach');
    console.log('post: ', post);
    request.del(base_url+'/'+post._id, function(err, response, body) {
      if (err) console.log('ERROR IN THE TEAR DOWN.');
      else { post = null; }
    });
  });

  it('returns a status code of 200', function(done) {
    expect(true).toBe(true);
    done();
    // request.get(base_url+'/'+post._id, function(err, response, body) {
    //   expect(response.statusCode).toBe(200);
    //   done();
    // });
  });
  it('returns the right post', function(done) {
    expect(true).toBe(true);
    done();
    // request.get(base_url+'/'+post._id, function(err, response, body) {
    //   expect(JSON.parse(body)).toEqual(post);
    //   done();
    // });
  });
});

Output:

~/code/study-buddies $ jasmine-node server
in afterEach
post:  undefined
Fin afterEach
post:  undefined
F

Failures:

  1) Posts GET /:id returns a status code of 200
   Message:
     TypeError: Cannot read property '_id' of undefined
   Stacktrace:
     TypeError: Cannot read property '_id' of undefined
    at null.<anonymous> (/Users/azerner/code/study-buddies/server/posts/post.spec.js:40:36)
    at Timer.listOnTimeout (timers.js:119:15)

  2) Posts GET /:id returns the right post
   Message:
     TypeError: Cannot read property '_id' of undefined
   Stacktrace:
     TypeError: Cannot read property '_id' of undefined
    at null.<anonymous> (/Users/azerner/code/study-buddies/server/posts/post.spec.js:40:36)

Finished in 0.02 seconds
2 tests, 4 assertions, 2 failures, 0 skipped


body:  { title: 'one', _id: '55b1aaca81a6107523693a00' }
body:  { title: 'one', _id: '55b1aaca81a6107523693a01' }
~/code/study-buddies $

in afterEach is logged before body:. That makes me think that the afterEach is running before the beforeEach. What is going on here?

Upvotes: 0

Views: 344

Answers (1)

brandonscript
brandonscript

Reputation: 73044

Use the done callback to run your beforeEach synchronously:

beforeEach(function(done) {
   var options = {
      uri: base_url,
      method: 'POST',
      json: {
        title: 'one'
      }
   };
   request(options, function(err, response, body) {
      console.log('body: ', body);
      if (err) console.log('ERROR IN THE SET UP.');
      else { post = body; }
      done();
   });  
});

Upvotes: 1

Related Questions