Jasmine的afterEach似乎在测试我的REST API之前在beforeEach之前运行

时间:2015-07-24 03:07:48

标签: javascript node.js jasmine

代码:

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();
    // });
  });
});

输出:

~/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之前记录

body:。这让我觉得afterEach正在beforeEach之前运行。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

使用done回调同步运行您的beforeEach:

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();
   });  
});