Pre-request error on Newman - Cannot read property 'set' of undefined

I am trying to run my postman collection from my CLI using Newman, but I keep getting this error
TypeError in prerequest-script. Kindly put me through on what I am not doing correctly. Below is my pre-request script:

    var seed = Math.floor(Math.random() * 899999999999 + 100000000000);
    var d = new Date();
    var sessionID = '{{source_bank_code}}' + d.getFullYear().toString().substr(-2)+("0"+(d.getMonth()+1)).slice(-2)+("0" + d.getDate()).slice(-2)+("0" + d.getHours()).slice(-2) + ("0" + d.getMinutes()).slice(-2)+("0" + d.getSeconds()).slice(-2) + seed;

    var beneficiary_account_number = "2345678907";


    pm.collectionVariables.set("session_id", sessionID);
    pm.collectionVariables.set("beneficiary_account_number", beneficiary_account_number); 
    pm.collectionVariables.set("name_enquiry_ref", sessionID);

At the end of the test, the failure detail says,
01. TypeError: Cannot read property 'set' of undefined at prerequest-script inside "Source Bank Agent / Transfers / Account Enquiry / Get Account Details (Valid)"

2 Likes

I see two possible problems:

  1. pm.collectionVariables.set is a newly introduced API and you need to update Newman to the latest version. Otherwise, it will not work.

This is causing the error “TypeError: Cannot read property ‘set’ of undefined”. pm.collectionVariables is undefined as it does not exist yet in your version of Newman.

  1. Just using double curly braces in a string (like {{source_bank_code}}) won’t motivate Postman to replace them for you.

You can use the pm.* API to fetch the respective value.

2 Likes

Thanks for your response.

The version of newman that I run on is 4.5.4 which is pretty recent. Nevertheless, I’ll try to update it to the latest version (v4.5.6) and see if it would handle it differently.

As regard the use of the double curly bracket to place variables in the script, it works just fine with postman, so I assumed newman shouldn’t have an issue with it. But also, I will do well to explore that option of fetching the value first and placing it in a variable local to the script.

I have tried getting rid of the double curly bracket. The error still persists.

@conigbinde I tried your Pre-request script with newman 4.5.6 and everything worked without issue.

Do confirm your newman install version as follows:

$ newman --version
4.5.6

If you are still on an older version, update as follows

$ npm install -g newman

Thanks all @amit for the reply. After updating my newman to the latest version, it worked without any issue.
I was only able to use the following command to update my newman:

$ npm install -g newman

My bad, I did not realise that you where using the string in the request somewhere.

1 Like

My bad! I incorrectly typed postman instead of newman
But glad you were able to update newman and get it to work.

1 Like