Postman – Async request within Test Function

I’ve been testing the asynchronous nature of the Postman sendRequest() function and I’m trying to get it working within an pm.test block but my initial efforts are failing

This is the first example to show the async nature of sendRequest()

for (let i = 1; i < 11; i++) {

    let testValue = `request${i}`

    let request = {
        url: 'https://postman-echo.com/get?test=' + testValue,
        method: 'GET',
    }

    pm.sendRequest(request, (err, res) => {
        if (err) {
            console.log(err);
        }
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(res).to.have.status(200);
            let resJson = res.json();
            console.log(resJson.args.test);
        });
    });

};

enter image description here

sendRequest now supports promises and top-level awaits, so this can be rectified by the following.

for (let i = 1; i < 11; i++) {
    const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);

    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

enter image description here

You can add a catch for some error handing.

for (let i = 1; i < 11; i++) {
    const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`).catch(error => console.log(error));
    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

or

for (let i = 1; i < 11; i++) {
    try {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
            let resJson = response.json();
            console.log(resJson.args.test);
        });
    } catch (error) {
        console.log(error);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(error, error.code).to.be.undefined;
        });
    }
};

Other versions that produce pretty much the same result.

const sendRequest = (req) => {
    return new Promise((resolve, reject) => {
        pm.sendRequest(req, (err, res) => {
            if (err) {
                console.log(err);
                return reject(err);
            }
            resolve(res);
        });
    });
};

(async () => {
    for (let i = 1; i < 11; i++) {
        let testValue = `request${i}`
        let request = {
            url: 'https://postman-echo.com/get?test=' + testValue,
            method: 'GET',
        }
        const response = await sendRequest(request); // wait for promise to be resolved before continuing
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
            let resJson = response.json();
            console.log(resJson.args.test);
        });
    }
})();
const sendRequest = (req) => {
    return new Promise((resolve, reject) => {
        pm.sendRequest(req, (err, res) => {
            if (err) {
                console.log(err);
                return reject(err);
            }
            resolve(res);
        });
    });
};

async function asyncCall(request, i) {
    const response = await sendRequest(request);
    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

for (let i = 1; i < 11; i++) {
    let request = {
        url: 'https://postman-echo.com/get?test=' + `request${i}`,
        method: 'GET',
    }
    await asyncCall(request, i);
};

The final version I ended up with.

async function sendRequest(request, i) {
    try {
        const response = await pm.sendRequest(request);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
        });
        return {
            'data': response,
            'status': "success"
        };
    } catch (error) {
        console.log(error);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(error, error.code).to.be.undefined;
        });
        return {
            "status": "error",
            "errorcode": error.code
        }
    }
};

for (let i = 1; i < 11; i++) {
    let response = await sendRequest(`https://postman-echo.com/get?test=request${i}`, i);
    if (response.status === "success") {
        console.log(response.data.json().args.test); // Postman Echo Response
    }
};

What I really want to do though is move the async sendRequest into the test block.

So if the request fails, it stops processing any more code

If you do the following, you get a syntax error.

for (let i = 1; i < 11; i++) {

    pm.test(`Request ${i} - status code is 200`, () => {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });

};

SyntaxError: await is only valid in async functions and the top level bodies of modules

If you do the following, it no longer errors, but the requests are no longer in order either.

for (let i = 1; i < 11; i++) {

    pm.test(`Request ${i} - status code is 200`, async () => {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });

};

Searching the Internet, I stumbled across the following.

https://jestjs.io/docs/asynchronous

So I then looked at the Postman docs which seems to indicate that its using the Mocha framework under the hood.

https://github.com/postmanlabs/postman-runtime/tree/develop/test

Another Internet Search later.

https://masteringjs.io/tutorials/mocha/async

This seems to indicate that I should be able to do something like I’m trying, but although I can get the code to run without errors, it’s never in order anymore.

Can someone please push me in the right direction on what I’m doing wrong here.