Home > Software design >  How to check if the response includes specified value and if so - end test in Postman
How to check if the response includes specified value and if so - end test in Postman

Time:01-12

I'm learning Postman test scripts and I am stuck with one exercise. I need to check if the response includes specified value (one of the planet from array is called Tatooine). Body response:

   "results": [
        {
            "name": "Tatooine",
            "rotation_period": "23",
            "orbital_period": "304",
            "diameter": "10465",
        {
            "name": "Alderaan",
            "rotation_period": "24",
            "orbital_period": "364",
            "diameter": "12500",
        },

I created this script:

const jsonData = pm.response.json();

pm.test("Your test name", function () {
    for (let i = 0; i <= jsonData.results.length; i  ) {
        pm.expect(jsonData.results[i].name).to.include("Tatooine")};

});

But I don't know how to get out of the loop and mark test as "passed" after finding searched value.

CodePudding user response:

I assume you want to verify that at least there is a name Tatooine.

Step 1: Get all names

const jsonData = pm.response.json();
let names = _.map(jsonData.results, "name");

Step 2: Validate the array names contains Tatooine

pm.test("Your test name", function () { 
  pm.expect(names).to.include("Tatooine")
});
  • Related