邮递员-比较两个忽略顺序的响应和一些特定属性

时间:2019-07-26 18:26:16

标签: json postman

我需要比较两个响应,忽略顺序,如果属性具有相同的值,则集中注意。另外,还要忽略某些特定属性(该属性包含在响应1中,但不应在响应2中)。

我已经尝试过深度相等,但这不是我想要的

->要将第一个响应保存在全局变量中:

pm.globals.set("response1", pm.response.json());

->要在第二个响应中进行比较:

pm.test("Compare responses", function(){    
    pm.expect(pm.response.json()).to.deep.equal(pm.globals.get("response1"));
});

编辑:响应还包含一个对象数组

1 个答案:

答案 0 :(得分:0)

我想出了一个解决方案。在请求前脚本上:

pm.globals.set("loadAsserts", function loadAsserts(){
   let asserts = {};
   let jsonData = JSON.parse(responseBody);

   asserts.areEqual = function areEqual(actual, expected, objectName) {
        pm.test(`Actual ${objectName} '` + actual + `' matches Expected ${objectName} '` + expected + `'`, () => {
            pm.expect(_.isEqual(actual, expected)).to.be.true;
        });
    }

    asserts.areArrayOfObjectsEqual = function areArrayOfObjectsEqual(actual, expected, objectName) {
        if (!_.isEqual(actual, expected)) {

            // Arrays are not equal so report what the differences are
            for (var indexItem = 0; indexItem < expected.length; indexItem++) {
                assert.compareArrayObject(actual[indexItem], expected[indexItem], objectName);
            }
        }
        else
        {
            // This fake test will always pass and is just here for displaying output to highlight that the array has been verified as part of the test run
            pm.test(`actual '${objectName}' array matches expected '${objectName}' array`);
        }
    }

    asserts.compareArrayObject = function compareArrayObject (actualObject, expectedObject, objectName) {
        for (var key in expectedObject) {
            if (expectedObject.hasOwnProperty(key)) {
                assert.areEqual(expectedObject[key], actualObject[key], objectName + " - " + key);
            }
        }
    }

    return asserts;
} + '; loadAsserts();');

tests['Asserts initialized'] = true;
pm.globals.set("actualResponse", pm.response.json());`

现在,当我想在响应中调用它时:

asserts.areEqual(actualResponse.id, expectedResponse.id, "id");