How can I compare request body and response body?

//Is equal to the request body and response body?
if (pm.response.code === 200) {

pm.sendRequest(utils.getApiUrl(pm.request) + pm.response.json(), (error, response) => {
    if (error) {
        console.log(error);
    } else {
        pm.test("Are there all of parameters - ", function () {
            pm.expect(response.json()).is.eql(pm.request.body.raw)
        })
    }
});

};

Hi @acihad

You could try something like this;

const myRequest = pm.request.toJSON().body.raw;
//Remove all characvters and formatting that are not part of the original request.
let myRequestFormatted = myRequest.replace(/[^a-zA-Z0-9":\[\]{},]/g, "");
console.log(myRequestFormatted);

const myResponse = pm.response.json();
console.log(JSON.stringify(myResponse));

if (myRequestFormatted === JSON.stringify(myResponse)){
    console.log("Request and Response MATCH");
}
else{
    console.log("Request and Response DONT MATCH");
}

Matched Output;

Unmatched Output;

1 Like

Hi @w4dd325 ,

Appreciated your answer. I have just carried out your codes but my request did not indicate on the console.

Looking at your screenshot I’d guess thats because your body (raw) is empty.

My code was based on the assumption that the request body was here;

1 Like

Hi @w4dd325 ,

Thank you for being so helpful.

Hi @w4dd325 ,

I have a question about parameter control. How can I check the parameters control whether are there name or description, etc. parameters in request?

Not sure I understand the question, could you be more specific?

Hi @w4dd325 ,

How can I check the propery control whether are there name or description, etc. properties in request? For instance, is there name property, and value control of the name property? I would like to carry these controls out separately.

Thank you for your time.

I’m not entirely sure what you mean by “property control”

But if you want to check that your objects and properties exist with certain values, you could do something like this;

const response = pm.response.json();

pm.test("API response contains the expected fields", () => {
  pm.expect(response).to.have.property("id", 0);
  pm.expect(response).to.have.property("name", "doggie");
  pm.expect(response).to.have.property("status", "available");
});

hi @w4dd325 ,

I would like to set all of the properties from collection to any request.

utils= {
control: function _isContains(json, keyname, value) {
return Object.keys(json).some(key => {
return typeof json[key] === ‘object’ ?
_isContains(json[key], keyname, value) : key === keyname && json[key] === value;
});
}

};

//Is equal to the request body and response body?
var expect = pm.variables.get(“keys”)

pm.test(“Are there all of parameters”, function() {
pm.expect(pm.response.json()).to.have.keys(expect);

});