vendredi 27 mai 2016

NodeJS - Testing an API with Request and Promise

I'm not an Javascript expert, and I failed to understand how to work some Js particularity.

I wanted to automated test, I dit it, it works. The algorithm is simple :

[for each] 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 + "] :\t\tok\t(" + expected + ')' );
    }else{
        msgError("["+KeyWord + "]\t\tERROR => " + error);
        msgError("Error result: \n" + body);
    }
});

But I want to split the test part, from the request, and manage it with 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));

But I have no idea how to get and give the testRequestResult() parameters (error, response, body)

The other point is that I'm pretty sure that all the reject will be concatenated and the result will automatically goes to the allErrors variable.

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

Will at the end show "1, 2, 3,".

But I can't explain why, and especially how?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire