gpt4 book ai didi

node.js - jasmine-node waitsFor() 停止所有 future 的运行()

转载 作者:搜寻专家 更新时间:2023-11-01 00:08:45 26 4
gpt4 key购买 nike

第一次运行创建用户,第二次运行从服务器获取用户。 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);
});
});
});
});

最佳答案

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

关于node.js - jasmine-node waitsFor() 停止所有 future 的运行(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com