Search code examples
javascriptpostmanpostman-collection-runnerpostman-pre-request-scriptpostman-testcase

Execute a request a given number of times (postman)


Related to:

https://stackoverflow.com/questions/36157105/postman-how-to-make-multiple-requests-at-the-same-time#:~:text=Just%20create%20a%20runner%20with,to%20bring%20up%20multiple%20instances.

but I need to make the same request a given number of times. E.g. for an endpoint:

(GET) http://localhost/gadgets/{{gadget_id}}/buy_gadget

the gadget_id variable can be read from a file but this leads to multiple GET requests with a different id. How can I make a predefined number of requests to the same endpoint with the same gadget_id?


Solution

  • You need to somehow get the gadget_id and the number of runs, since that is not part of the core question here, I'm simply setting those as environment variables.

    In the pre-request script, if an environment variable counter is not existing, it is being set to 1. If it is existing, it is being increased by 1:

    pm.environment.set("gadged_id", 1234);
    pm.environment.set("numberOfRuns", 3)
    
    if (!pm.environment.get("counter")) {
        pm.environment.set("counter", 1);
    } else {
        let counter = parseInt(pm.environment.get("counter"));
        counter++;
        pm.environment.set("counter", counter);
    }
    

    In the test tab, it is being checked if the number of runs has already been reached. If not, the same request is being called again via postman.setNextRequest() (you need to adabt the parameter value of postman.setNextRequest() to the name of your request). If it has been executed often enough, the counter variable is unset:

    let numberOfRuns = parseInt(pm.environment.get("numberOfRuns"));
    let counter = parseInt(pm.environment.get("counter"));
    
    if (counter < numberOfRuns) {
        postman.setNextRequest("buyGadget");
    } else {
        pm.environment.unset("counter")
    }