PostMan Test scripts: Inspecting contents of response JSON

瘦欲@ 提交于 2019-12-11 12:13:35

问题


PostMan 6.0.10 here. I'm trying to understand how to write test scripts a little better, and after reading their otherwise superb documentation I still have some confusion surrounding how to query & examine the JSON response coming back from requests.

Specifically, given the following snippet of JavaScript:

pm.test("Verify the contents of the response payload are correct", function () {
    // ???
});

I need to be able to query the response JSON and:

  • Determine if the response is a single JSON object or an array of JSON objects
  • If its an array, determine the size (# of elements in the array)
  • Else if its a single object, I need to be able to query that object for specific fields (say, a field called "fizzbuzz") and obtain the values and JSON types (string, number, bool, null) of those fields

Scenario #1: JSON response is an array

Example:

[
    {
        "fizz": "buzz",
        "foo": 53
    },
    {
        "fizz": "bozz",
        "foo": 291
    }
]

Scenario #2: JSON response is a single object

Example:

{
    "fizz": "buzz",
    "foo": 293
}

Any ideas how this JSON inspection of the response payloads can be performed?


回答1:


This is basic but should work to get the dynamics:

pm.test("Verify payload of example one",  () => {
    pm.expect(pm.response.json()[0].fizz).to.equal('buzz')
    pm.expect(pm.response.json()[0].foo).to.equal(53)
    pm.expect(pm.response.json()[1].fizz).to.equal('bozz')
    pm.expect(pm.response.json()[1].foo).to.equal(291)
});

pm.test("Verify payload of example two",  () => {
    pm.expect(pm.response.json().fizz).to.equal('buzz')
    pm.expect(pm.response.json().foo).to.equal(293)
});

Might be worth researching some basic JavaScript and how to parse JSON objects.



来源:https://stackoverflow.com/questions/49586400/postman-test-scripts-inspecting-contents-of-response-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!