Facing - unexpected token u in json at position 0 at test-script, while running collection using newman script or as a library

I am trying to my API collection using newman as a library. Based on reference link below, i have created script (please find below snippet for the same) and trying to run my collection outside postman.

Reference Link : Postman: How to Write Files to Disk? | by Valentin Despa | APIs with Valentine | Medium

Code Snippet:

const newman = require('newman'),
fs = require('fs');

newman.run({
    collection: require('./postman_collection.json'),
	insecure: true,
	globals: require('./globals.json'),
	iterationData: require('./InputData.json'),
	folder: 'TC05',
    reporters: 'cli'
}).on('beforeRequest', function (error, args) {
    if (error) {
        console.error(error);
    } else {
        fs.writeFile(`./writeToFile/${args.item.name}-request.json`, args.request.body.raw, function (error) {
            if (error) { 
                console.error(error); 
            }
        });    
    }
}).on('request', function (error, args) {
    if (error) {
        console.error(error);
    }
    else {
		if(`${args.item.name}` == `genLetter`){
			fs.writeFile(`./writeToFile/${args.item.name}-response.docx`, args.response.stream, function (error) {
            if (error) { 
                console.error(error); 
            }
			});
		}
		else{
        fs.writeFile(`./writeToFile/${args.item.name}-response.json`, args.response.stream, function (error) {
            if (error) { 
                console.error(error); 
            }
        });        
    }
}
});

During run i see some / few of tests passed with scripts assertions written but for most of API requests its failing due to below error. Please find below snippet for errors.

image

image

On the other hand - i have also run my collection using newman cli commands (like using - g for globals, -d for data etc.) and all API steps in collection were passed. But i am using script approach because i wanted to save request and response for each API test step in my collection.

Can any one guide me in right direction on how i can overcome on this issue as i am consistently facing the issue as captured.

Hi @ashkht !

So it seems like the issue that you’re facing could be related to the way you’re handling the requests and responses within the newman events.

The error "Unexpected token u in json at position 0" suggests you’re trying to parse undefined as JSON in your test or script. This usually happens when the API response isn’t JSON, is empty, or if Postman variables aren’t resolving correctly.

Steps to Resolve:

  1. Log the Response: Before parsing, print the response to understand its content:
    console.log(pm.response.text());
    
  2. Safe JSON Parsing: Before parsing, ensure the response is valid JSON:
    let responseBody = pm.response.text();
    if (responseBody && responseBody !== 'undefined') {
        let jsonData = JSON.parse(responseBody);
    }
    
  3. Check Endpoint Behavior: Ensure your API is supposed to return JSON. A 200 status code doesn’t always guarantee a JSON response.
  4. Inspect Scripts: Check both pre-request and test script sections in Postman for outdated or conflicting scripts.
  5. Content-Type Header: Ensure the API’s response header includes Content-Type: application/json if you’re expecting JSON.

Hope this helps! :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.