Thomas
Thomas

Reputation: 1

How to validate JSON response using JSON test data file?

Having JSON response with nested elements. I would like to validate it against JSON test data using Postman and test functions.

For the moment I can easily reach it by hardcoding:

const jsonData = pm.response.json();
        
pm.expect(jsonData.items[0].title).to.eql(pm.iterationData.get("title"));
pm.expect(jsonData.items[1].title).to.eql(pm.iterationData.get("title"));

here is my JSON test data file:

[
  {
    "title": "Title1"
  },
  {
    "title": "Title2"
  }
]

Question is how to validate it in different way, but still using JSON test data structure? e.g. if I will have like 100 titles to verify in JSON test data, no need to of course put 100 same lines...

Thanks in advance

Upvotes: 0

Views: 57

Answers (2)

Ganesh Todkar
Ganesh Todkar

Reputation: 537

For Postman scripts:

// Get the response JSON
const jsonData = pm.response.json();

// Load the test data
const testData = pm.variables.get("testData");

// Parse the test data if it's a JSON string
const parsedTestData = JSON.parse(testData);

// Ensure the response items length matches the test data length
pm.test("Response items count matches test data count", function () {
    pm.expect(jsonData.items.length).to.eql(parsedTestData.length);
});

// Iterate over each item in the test data and validate against the response
parsedTestData.forEach((testItem, index) => {
    pm.test(`Title of item ${index} matches`, function () {
        pm.expect(jsonData.items[index].title).to.eql(testItem.title);
    });
});

Hope this helps

Upvotes: 0

Ganesh Todkar
Ganesh Todkar

Reputation: 537

Iterate over the JSON test data Use a loop to iterate through the test data and validate the corresponding elements in the response.

// Your JSON data
const jsonData = [
  {
    "title": "Title1"
  },
  {
    "title": "Title2"
  },
  {
    "title": "Title3"
  }
];

// Iterate over the JSON data
jsonData.forEach((item, index) => {
  console.log(`Title of item ${index + 1}: ${item.title}`);
});

You can add conditions accordingly

Upvotes: 0

Related Questions