Search code examples
javascriptjsonpostmanpostman-testcase

In postman, how can i check if the values in the response is same as that of the request irrespective of case or the order for an array?


I have a request similar to

{
    "Name":"123",
    "Age":"1234",
    "Phone":"12345",
    "RequestedABC":{"XYZ":"111abc","Qwe":"222abc","ZXC":"333def"}
}

Response is

{
    "Name": "123",
    "AllowedABC": {
        "XYZ": "111abc",
        "ZXC": "333def",
        "QWE": "222abc",
        }
}

I want to test whether the allowed ABC is same that of the requested ABC. Meaning that i want to assert that all key value pairs in the response is same as that in the requested one irrespective of the case or the order in which they are listed in the response. The provided example would be a pass scenario. I tried

var body = JSON.parse(request.data);
var jsonData = JSON.parse(responseBody);
pm.test("Granted ABC is same as requested ABCTest", () => {    
    pm.expect(jsonData.AllowedABC).to.eql(body.RequestedABC);    
});

But im getting an error

AssertionError: expected{Object(XYZ,ZXC...)} to to deeply equal {Object (XYZ,Qwe,...)}


Solution

  • This will work - not sure how to.eql works with objects, but this results in testing strings instead

    const responseData = {
        "Name": "123",
        "AllowedABC": {
            "XYZ": "111abc",
            "ZXC": "333def",
            "QWE": "222abc",
            }
    }
    const requestData = {
        "Name":"123",
        "Age":"1234",
        "Phone":"12345",
        "RequestedABC":{"XYZ":"111abc","Qwe":"222abc","ZXC":"333def"}
    };
    
    const sorter = ([a], [b]) => a.localeCompare(b);
    const transformer = obj => Object.entries(obj).map(([k, v]) => [k.toUpperCase(), v.toUpperCase()]).sort(sorter).join();
    
    const requestABC = transformer(requestData.RequestedABC);
    const responseABC = transformer(responseData.AllowedABC);
    
    console.log(requestABC);
    console.log(responseABC);
    console.log(requestABC === responseABC);

    In your code you would do

    var body = JSON.parse(request.data);
    var jsonData = JSON.parse(responseBody);
    
    const sorter = ([a], [b]) => a.localeCompare(b);
    const transformer = obj => Object.entries(obj).map(([k, v]) => [k.toUpperCase(), v.toUpperCase()]).sort(sorter).join();
    
    const requestABC = transformer(body.RequestedABC);
    const responseABC = transformer(jsonData.AllowedABC);
    
    pm.test("Granted ABC is same as requested ABCTest", () => {    
      pm.expect(responseABC ).to.eql(requestABC);    
    });
    

    Hope that makes sense now