第一次运行创建一个用户,第二次运行从服务器获取用户。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);
});
});
});
});发布于 2017-02-23 00:49:31
使用可以传递给beforeEach的done()函数可能更简单,我已经尝试将其应用到下面的示例中;
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();
});
});https://stackoverflow.com/questions/17201466
复制相似问题