NodeJS-使用请求和承诺测试API



我不是Javascript专家,我不知道如何处理Js的一些特殊性。

我想自动化测试,我编辑它,它工作。算法很简单:

[foreach]test[do]request()[then]testRequest()

function requestFunction(url, KeyWord, path, expected){
request( url + path + '/', function (error, response, body) {
if (!error && response.statusCode == expected) {
msgSuccess("["+KeyWord + "] :ttokt(" + expected + ')' );
}else{
msgError("["+KeyWord + "]ttERROR => " + error);
msgError("Error result: n" + body);
}
});

但是我想从请求中分离测试部分,并用promise管理它

var promise1 = new Promise(requestFunction(url, KeyWord, path, expected));
var promise2 = new Promise(testRequest(error, response, body, expected));
Promise.all([promise1, promise2]).then(
console.log(KeyWord + " ok"),
showOnlyTheError(allErrors));

但我不知道如何获取并给出testRequestResult()参数(错误、响应、正文)

另一点是,我非常确信所有拒绝都将被连接结果将自动转到allErrors变量

eg: testRequest(...){ reject("[Error]" + **ErrorNumbers** + ", ")};

将在最后显示"1,2,3,">

但我无法解释为什么,尤其是如何解释?

提前谢谢。

[编辑]我试过了:

var arrayOfPaths= [
'Ping',
'PING'];
var promises = arrayOfPaths.forEach(function(path){
return new Promise(resolve => {
msgStatus(url+path+'/');
return resolve(request(url+path+'/'));
});
});
Promise.all(promises).then(
function(result){
//after all promises resolve do something with array of results
msgStatus("result " + result.body );
}
).catch(function(result){
//if any of the promises fail they will be handled here
//do something with errors
msgError("err " + result.error );
}
);

=>但它总是在捕获部分消失,并出现以下错误:

错误未定义

我的服务器收到了一个很好的请求,并发回了一个正常的响应(statusCode=200)

没有必要将测试与请求分离。

如果您有10个执行api调用的测试,则需要执行Promise.all([request1,request2,...])。因为api调用是异步的,并且将在不同的时间解析promise。

我建议使用thens来等待响应,以解决可能看起来像这样的承诺:

new Promise(function(resolve){
request( url + path + '/', function (error, response, body) {
return resolve({error:error,response:response,body:body})
}
}.then(function(result){
if (!result.error && result.response.statusCode == expected) {
msgSuccess("["+KeyWord + "] :ttokt(" + expected + ')' );
}else{
msgError("["+KeyWord + "]ttERROR => " + error);
msgError("Error result: n" + result.body);
}
})

多个请求看起来像这个

var promises = arrayOfUrlPaths.foreach(url){
return new Promise(resolve => {
return resolve(request(url))
}
}
Promise.all(promises).then(function(result){
//after all promises resolve do something with array of results
}.catch(function(result){
//if any of the promises fail they will be handled here
//do something with errors
})

)

最新更新