3

第一次运行创建一个用户,第二次运行从服务器获取用户。WaitsFor 应该导致第二次运行等到第一次运行完成。但是,当运行 node-jasmine 时,测试在打印后停止before: 51c21c1ef463390000000008,而不发出 get 请求。

我试过去掉waitsFor,但这会导致get请求在post请求之前发生,这会导致它失败,因为它依赖于新用户的userid.

这是怎么回事?

var request = require('request');

describe("User", function(){
  var userid;
  it ("creates user", function(){

    runs(function(){
      var username = 'test' + Math.floor((Math.random()*100000)+1);

      var body = {
        username: username,
        email: username + "@test.com",
        password: username + "@test.com"
      };

      var options = {
        uri: 'http://localhost:3000/api/user',
        method: 'POST',
        headers: {
          'Content-type': 'application/json'
        },
        body: JSON.stringify(body)
      };


      request(options, function(err, res, body) {
        expect(res.statusCode).toEqual(200);
        console.log(body);
        var newUser = JSON.parse(body)[0];
        userid = newUser._id;
        console.log("before: "+ userid);

        expect(newUser.toBeTruthy());
      });
    });

    waitsFor(function() {
      console.log(typeof userid != "undefined");
      return (typeof userid != "undefined");
    }, "userid is never set", 10000);

    //it ("gets user", function() {
    runs(function(){
      expect(userid).toBeFalsy();
      console.log("this: "+userid);
      request.get("http://localhost:3000/api/user/" + userid, function(err, res, body){
        console.log("statuscode:" + res.statusCode);
        expect(res.statusCode).toEqual(2000);
        expect(body).toBeTruthy();
        console.log('Response: ' + body);
      });
    });
  });
});
4

1 回答 1

0

done()使用可以传入的函数可能更容易beforeEach,我尝试将其应用于下面的示例;

var request = require('request');

describe("User", function() {
  var getBody;
  var getRes;
  var newUser;
  var postBody;
  var postRes;
  var userId;

  beforeEach(function(done) {
    var username = 'test' + Math.floor((Math.random() * 100000) + 1);

    request({
      uri: 'http://localhost:3000/api/user',
      method: 'POST',
      headers: {
        'Content-type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        email: username + "@test.com",
        password: username + "@test.com"
      })
    }, function(err, _postRes, _postBody) {
      postRes = _postRes;
      postBody = _postBody;
      newUser = JSON.parse(postBody)[0];
      userId = newUser._id;

      request.get("http://localhost:3000/api/user/" + userId, function(err, _getRes, _getBody) {
        getRes = _getRes;
        getBody = _getBody;
        done();
      });
    });
  });

  it("creates user", function() {
    expect(postRes.statusCode).toEqual(200);
    expect(newUser.toBeTruthy());
    expect(getRes.statusCode).toEqual(2000);
    expect(getBody).toBeTruthy();
  });
});
于 2017-02-22T16:49:30.720 回答