How to verify full body response within a Pre requisite script and compare with response body?

Hi ,
I have 67 branches below and i have added a variable within
Pre - Requisite script
var expectedJsonBody =

[

{

    "siteId": 685,

    "siteName": "Saint Francis Hospital-Memphis",

    "hcoid": 2659,

    "defaultSite": false,

    "address": {

        "address1": "5959 Park Avenue",

        "address2": null,

        "city": "Memphis",

        "state": "TN",

        "zip": "38119-5198"

    }

},

{

pm.environment.set(“ExpectedSitesTodisplay”, JSON.stringify(expectedJsonBody));

and in the test of the script i have
pm.test(“Verify Expected Results sites match the Actual Results of all sites for Darlene”), function(){

pm.expect(savedData.response).to.equal(“ExpectedSitesTodisplay”);

};

it is showing up as pass, but when i enter
ExpectedSitesTodisplay variable within the console, its saying undefined,
and if i change something in the pre requisite script and click send it should fail but it still passes…

Your test isn’t testing the variable you set in your prerequest script.

pm.test(“Verify Expected Results sites match the Actual Results of all sites for Darlene”), function(){
  const expectedSitesToDisplay = pm.environment.get('ExpectedSitesTodisplay');  
  pm.expect(savedData.response).to.equal(expectedSitesToDisplay);
};

Hi Thanks a lot ,

I did try this and am getting it to pass, but lets say if i change one parameter or letter in the pre requisite script it should fail but its not failing … so meaning its not comparing actual and expected.

You still aren’t using the variable in your test.

You need to take off the quotes around the variable name

pm.expect(savedData.response).to.equal(ExpectedSitesTodisplay);

Hi, I did try that …
ill break it down maybe its something in the pre requisite script that should not be there:

Pre requisite script

var expectedJsonBody =
[

{

    "siteId": 685,

    "siteName": "Saint Francis Hospital-Memphis",

    "hcoid": 2659,

    "defaultSite": false,

    "address": {

        "address1": "5959 Park Avenue",

        "address2": null,

        "city": "Memphis",

        "state": "TN",

        "zip": "38119-5198"

    }

},

{

// pm.environment.get(“expectedJsonBody”);

pm.environment.set(“ExpectedSitesTodisplay”, JSON.stringify(expectedJsonBody));

in Test of other script:
let response = pm.response.json();

savedData = JSON.stringify(response);

pm.environment.set(“savedData”, savedData);

var jsonData = JSON.parse(savedData)

pm.test(“Verify Expected Results sites match the Actual Results of all sites for Darlene”), function(){

const ExpectedSitesTodisplay = pm.environment.get(‘ExpectedSitesTodisplay’);

pm.expect(savedData.response).to.equal(ExpectedSitesTodisplay);

};

Its passing but if i change the value in the pre req script , it does not fail it still passes…

I’m curious what you’re doing with the savedData variable. Is that the response of the request you are testing?

Or is it the response of a different test? I’m not sure why you’re setting it in an environment variable.

Maybe some screenshots of what this looks like in Postman would help.

Sure,

I was trying to get the full response body through the SavedData (actual response body) and compare it to the pre requisite variable (ExpectedSitesTodisplay) (expected) (pre requisite)

when i do this it passes, but if i change anything on the pre requsite script it still passes which it should not.


I changed the saint to faint and it still passed

I found this from this forum

Did that solve your problem?

hi Allen,

no it did not the part where i compare the response body with the variable is still not working …
i tried the code i wrote but still isn’t working.

I’m clearly missing something. What are you trying to do in a pre-request script? All your screenshots show test scripts.

How many requests are you running? 1, 2, 3…?

Hi, for the pre requesite script i have copied the full response body … and pasted it within the pre requisite script and then i want to verify the pre requisite script response body matches the response body within the get Request .

Just one GET request (Actual) , Pre req of that get Request (Expected) …

Ok I think I’m starting to get it now.

So you are running this test to make sure the schema and values don’t change over time?

Hi, Yes that is correct… i already tested to see if the response body is correct today , i want to ensure a week from now i am getting the same …

Then you should not be doing this in a pre-request script. You should be setting the variable in the test scripts which run AFTER the request is executed.

Are you wanting to validate only the schema or do you also want to validate the data for this specific request?

Hi not the schema too much more the data all of the data … how would i go about doing this …?

Personally, I would save off the values I want to check in the tests tab.

Then the next time the collection runs, you can compare the current values with the old values, and save off the new ones as well.

I added comments to parts of this snippet that you have provided.

change last line to
pm.expect(response).to.deep.equal(ExpectedSitesTodisplay);
or
pm.expect(response).to.deep.include(ExpectedSitesTodisplay);

Postman use the CHAI assertion library - Expect / Should - Chai
Read the examples there and this should help.

If you need to check also data by hand I can share this script

Save test function as variable
Save in Collection, Directory, folder some other test

pm.globals.set('helper', function loadhelper() {

 let helper = {};

helper.test = (model, response) => {
// you can manually provide nested object instead of whole response. 
        if(response == null)
            response = pm.response.json()

        for (var x in model) { //It's  list of keys of model json - the first level. any nested objects are check deeply. 
// the X is single field from model to be validated. . You can do it from response to model. I prefer to check that way. As response may have audit fields like created by created date and other 
            try {

                if(model[x] == null){

                    pm.test("Model null in respons - " + x, function () {

                        pm.expect(response[x]).to.be.null;  

                    });                     

                } else if (x.includes("date") || x.includes("Date")) {
// dates must be in same format to be compared 
                    let res = new Date(response[x]).toISOString(); 

                    let mod = new Date(model[x]).toISOString();

                    pm.test("Model match response - date of " + x, function () {

                        pm.expect(mod).to.equal(res);

                    });

                } else if (x.includes("id") || x.includes("Id")) {
                    //for debug if failed

                    // console.log("id " +  x ) 

                    // console.log("id slice " +  x.slice(0,-2) )
                   // if you have nested response 
                    if (x === "OtherUnitId") { // If Model and respons name does not equal but data should be checked. This is for exceptions that are constant rather than unexpected

                        pm.test("Model match response - Id of object " + x, function () {
                            // ParseInt is necessary if you run test from newman. There everything is converted to string.... don't ask why ... but parse is necessary   
                            pm.expect(parseInt(model[x])).to.equal(response["thatUnit"].id);

                        });

                    // if you have flat response
                    } else {

                        pm.test("Model match respons - Id of " + x, function () {

                            pm.expect(parseInt(model[x])).to.equal(parseInt(response[x]));

                        });

                    }  else { // this 'else' or above must be deleted. 
                   // any other nested 'ID check' field if you have flat response remove the slice and '.id'
                        pm.test("Model match respons - Id of " + x, function () {

                            pm.expect(parseInt(model[x])).to.equal(response[x.slice(0, -2)].id);

                        });

                    }

                }

                else if (typeof(model[x]) == typeof({}) && model[x] != null ){                    

                    pm.test("Model deep match respons - Field " + x, function (){                        

                        pm.expect(model[x]).to.deep.include(response[x]);

                    });
                    // here you can call recursion to this method and check deeply nested object. But it's danger zone :) 

                }

                else { // any other field, as strings.... mostly stings 

                    pm.test("Model match respons - Field " + x, function () {

                        pm.expect(model[x]).to.equal(response[x]);

                    });

                }                

            }

            catch (e) { // debugging purpose 

                pm.test("ERR No such field in response " + x, function () {

                    pm.expect.fail("Err:" + e);

                });

            }

        }

    }

 return helper;

} + '; loadhelper();');

Usage in test

var model = JSON.parse(pm.collectionVariables.get("XYZ_Model"));

// Use helper function from variables 

const helper = eval(pm.globals.get("helper"));

pm.test("Validate Model", helper.test(model));
pm.test("Validate Model", helper.test(model.nestedResource, pm.response.json().nestedResource)); // instead of recursion in main helper function as it is danger zone. 

Have a nice day :slight_smile: