Pm.test not initialized inside pm.sendRequest

Hi everyone, so I’m trying to use pm.test inside pm.sendRequest, and it appears that the pm.test isn’t initialized. Moreover, I’m trying to console.log the response, and yet again nothing happens (response, inside pm.sendRequest and outside of pm.test, isn’t printed to the console). Here is my code:

const passengersUrl = pm.variables.replaceIn("localhost:5000/Users/type=2&limit=20&page=1");
pm.sendRequest(passengersUrl), (error, response) => {
    if (error) {
        console.log(error);
    }

    pm.test("Get all drivers users route returns only drivers", () => {
        const responseJson = response.json();
        const usersArray = responseJson.data.users;
        usersArray.forEach(e => {
            for (const [key, value] of Object.entries(e)) {
                if (key == 'type') {
                    pm.expect(value).to.eql(1)
                }
            }
        })
    });
}

I was using the following documentation example: https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#sending-requests-from-scripts

Any suggestions? :thinking:

Hey @barakbs1 :wave: Welcome to the Postman community :tada:

I think the bracket after passengerUrl is causing the issue. Try the following:

const passengersUrl = pm.variables.replaceIn("localhost:5000/Users/type=2&limit=20&page=1");
pm.sendRequest(passengersUrl, (error, response) => {
    if (error) {
    console.log(error);
    }

    pm.test("Get all drivers users route returns only drivers", () => {
        const responseJson = response.json();
        const usersArray = responseJson.data.users;
        usersArray.forEach(e => {
            for (const [key, value] of Object.entries(e)) {
                if (key == 'type') {
                    pm.expect(value).to.eql(1)
                }
            }
        })
    });
})
2 Likes

Yes, that did the job! thank you very much!

1 Like