JS磁带 – 等待以前的asynchronoustesting完成移到下一个testing

我是与TAPE JS进行testing的新手。 我已经完成了所有的设置和工作,并且在定期testing中工作正常。 但是我试图testing一个独特的基于REST API的产品,这个产品依赖于在下一次调用之前已经完成的某些调用具有成功调用所需的信息。

所以这里是我想要工作的前两个电话:

var SessionId; test('beginIqsSession', function (assert) { assert.plan(1); var requestData = {"ProductDataArray":{"Feid":"GIQNY","AltData":"SaneID:null","Debug":"false","PageId":"1.1"}}; request({ url: 'http://192.168.99.100/Iqs/api.php/beginIqsSession', method: "POST", json: requestData }, function(error, response, json){ if(json.responseDataPayload.SessionId) { SessionId = json.responseDataPayload.SessionId; assert.equal(1,1); } }); assert.end(); }); test('validateAddress', function (assert) { assert.plan(2); console.log("Retrieving validateAddress response"); var requestData = {"SessionId":SessionId,"ValidateAddressDataArray":{"PropertyStreetNumber":"20671","PropertyStreetName":"mountain vista dr","PropertyCity":"anchorage","PropertyState":"AK","PropertyZipCode":"99577"}}; console.log(SessionId); request({ url: 'http://192.168.99.100/Iqs/api.php/validateAddress', method: "POST", json: requestData }, function (error, response, body) { if (!error) { console.log(body); } else { console.log("error: " + error) } }); assert.end(); }); 

所以基本上在上面的代码中,我试图testingbeginIqsSession,等待它的响应,并存储来自该响应的未来呼叫需要被发送的一段数据。

在validateAddress中,你会看到我正在尝试传递前一个调用中返回的SessionId,但是因为这个testing正在与前一个testing同时运行,所以这个variables仍然是空的。 我怎样才能使第二个电话,以及所有未来的电话,等待以前的电话运行?

assert.plan显然不以这种方式工作。

你可以使用Promise API

 var SessionId; let p1 = new Promise((resolve, reject) => { test('beginIqsSession', function (assert) { assert.plan(1); var requestData = {"ProductDataArray":{"Feid":"GIQNY","AltData":"SaneID:null","Debug":"false","PageId":"1.1"}}; request({ url: 'http://192.168.99.100/Iqs/api.php/beginIqsSession', method: "POST", json: requestData }, function(error, response, json){ if(json.responseDataPayload.SessionId) { SessionId = json.responseDataPayload.SessionId; assert.equal(1,1); resolve(SessionId); } }); assert.end(); }); }) p1.then((SessionId) => { test('validateAddress', function (assert) { assert.plan(2); console.log("Retrieving validateAddress response"); var requestData = {"SessionId":SessionId,"ValidateAddressDataArray":{"PropertyStreetNumber":"20671","PropertyStreetName":"mountain vista dr","PropertyCity":"anchorage","PropertyState":"AK","PropertyZipCode":"99577"}}; console.log(SessionId); request({ url: 'http://192.168.99.100/Iqs/api.php/validateAddress', method: "POST", json: requestData }, function (error, response, body) { if (!error) { console.log(body); } else { console.log("error: " + error) } }); assert.end(); }); });