茉莉'在测试我的REST API时,s afterEach似乎在beforeEach之前运行

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

本文关键字:afterEach beforeEach 运行 测试 我的 API REST 茉莉      更新时间:2023-09-26

代码:

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 $

CCD_ 1记录在CCD_ 2之前。这让我认为afterEachbeforeEach之前运行。这是怎么回事?

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