PostMan 6.0.10测试脚本编写:如何查询与检查响应JSON
Got it, let's break down how to write those test scripts for Postman 6.0.10 to check your JSON responses properly. I'll walk you through verifying if the response is a single JSON object, plus some common related checks you might need.
First: Get Parsed JSON from the Response
Before you can check anything, you need to parse the response body into a usable JavaScript object. Postman makes this super straightforward with:
const responseJson = pm.response.json();
This line takes the raw response body, parses it as JSON, and stores it in the responseJson variable for easy access.
Test 1: Verify Response is a Single JSON Object
To confirm the response is a single object (not an array, null, or other data type), you'll need to check three things:
- The parsed value is an
objecttype - It's not
null(sincetypeof nullincorrectly returnsobjectin JS) - It's not an array (arrays are also considered
objecttypes in JS)
Here's the complete test script:
pm.test("Verify the response is a single JSON object", function () { const responseJson = pm.response.json(); // Check the type is object pm.expect(typeof responseJson).to.eql('object'); // Ensure it's not null pm.expect(responseJson).to.not.be.null; // Confirm it's not an array pm.expect(Array.isArray(responseJson)).to.be.false; });
Bonus: Check Specific Fields in the JSON Object
Once you've confirmed it's a single object, you'll often want to verify specific fields exist and have the correct values/types. For example, if your response should have an id (number) and email (string) field:
pm.test("Verify required fields exist and have valid types", function () { const responseJson = pm.response.json(); // Check that the "id" property exists and is a number pm.expect(responseJson).to.have.property('id'); pm.expect(typeof responseJson.id).to.eql('number'); // Check that the "email" property exists and is a string pm.expect(responseJson).to.have.property('email'); pm.expect(typeof responseJson.email).to.eql('string'); // Optional: Check that the email matches a valid format pm.expect(responseJson.email).to.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/); });
A Quick Note on Assertions
Postman uses the Chai Assertion Library under the hood with pm.expect(), so you can use all the standard Chai syntax for more complex checks (like equality, ranges, includes, etc.). This gives you tons of flexibility for testing your responses.
内容的提问来源于stack exchange,提问作者smeeb

