How to Use Assertions
What is an Assertion
Assertions are generally used in post-response scripts to verify whether the response results meet expectations.
During collaborative development, version upgrades, server upgrades, and API responses, there may be inconsistencies with our expected results due to some bugs. In order to facilitate developers and testers to discover bugs more quickly and ensure the quality and progress of the entire product, we have introduced the assertion feature.
Define test cases
Verify test cases
For example, the interface returns:
{
"args": {},
"data": "",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Cache-Control": "no-cache",
"Cookie": "freeform=loseCookie%3Dgin",
"Host": "httpbin.org",
"Token": "nalcjarkarkgaremvavnaerr",
"User-Agent": "EchoapiRuntime/1.1.0",
"X-Amzn-Trace-Id": "Root=1-66b32552-37b5e0ea704f77fc437d8a92"
},
"json": null,
"method": "GET",
"origin": "114.242.33.198",
"url": "https://httpbin.org/anything"
}
Define Assertion Content:
pm.assert('response.raw.status==200');
pm.assert('response.raw.type=="json"');
pm.assert('response.json.errcode==0');
pm.assert('response.raw.responseTime<100');
pm.assert('response.json.header.Host=="echo.echoapi.com"');
After clicking the send button:
Green indicates that the test has passed, and red indicates that the test has failed.
Special Note: Each test case must be on one line and cannot wrap.
Example: pm.assert('response.json.header.Host=="echo.echoapi.com"');
1) response.json.header.Host refers to the Host field in the header array of the response JSON,
2) It must all be 1 to pass.
Common test assertions can be obtained through post-response scripts: (Assertion Examples)
Using EchoAPI's Assertion Format
// Check if the response body contains a specific string
pm.assert('response.raw.responseText=="test"'); // Check if the response text is equal to the "test" string
pm.assert('response.raw.responseText.indexOf("test") > -1'); // Check if the response text contains the "test" string
// Check if a returned JSON value equals the expected value
pm.assert('response.json.hasOwnProperty("errcode")'); // Check if the returned JSON object has the "errcode" field
pm.assert('response.json.errcode=="success"'); // Check if the "errcode" field in the returned JSON object equals the "success" string
pm.assert('response.json.errcode.indexOf("success") > -1'); // Check if the "errcode" field in the returned JSON object contains the "success" string
pm.assert('response.json.errcode!="success"'); // Check if the "errcode" field in the returned JSON object is not equal to the "success" string
pm.assert('response.json.errcode>=1'); // Check if the "errcode" field in the returned JSON object is greater than or equal to 1
pm.assert('response.json.errcode==null'); // Check if the "errcode" field in the returned JSON object is null
// Test if a certain element in the response Headers exists (e.g., Content-Type)
pm.assert('response.headers.hasOwnProperty("content-type")');
// Verify if the Status code (response code) is equal to 200
pm.assert('response.raw.status==200');
// Verify if the Response time (response duration) is greater than or equal to a certain value
pm.assert('response.raw.responseTime>=100');
Using Postman's Assertion Format
Fully compatible with Postman's assertion syntax.
Test Script Example
Hello World! The First Test Script
To write your first test script, open a request in EchoAPI and then select the "Post-response" tab. Add script and enter the following JavaScript code:
pm.test("Status Code is 200", () => {
pm.expect(pm.response.code).to.eql(200);
});
This test checks the response code returned by the API. If the response code is 200, the test will pass; otherwise, it will fail. Select send, and then check the assertion results in the "Test Results" section on the left.
Construct your test assertions in various ways to suit your logic and preferences for the output of results. The following code is another method to implement the same test as the above code using the expect syntax:
pm.test("Status code is 200", () => {
pm.expect(pm.response.code).to.eql(200);
});
Using Multiple Assertions
Your test can include multiple assertions as part of a single test. Use it to group related assertions together:
pm.test("The response has all properties", () => {
//parse the response JSON and test three properties
const responseJson = pm.response.json;
pm.expect(responseJson.type).to.eql('vip');
pm.expect(responseJson.name).to.be.a('string');
pm.expect(responseJson.id).to.have.lengthOf(1);
});
If any of the included assertions fail, the entire test will fail. All assertions must pass for the test to be successful.
Parsing Response Body Data
To make assertions about your response, you first need to parse the data into a JavaScript object that your assertions can use.
To parse JSON data, use the following syntax:
const responseJson = pm.response.json();
To parse XML, use the following:
const responseJson = xml2Json(pm.response.text());
To parse CSV, use the CSV parsing utility:
const responseJson = csv2array(pm.response.text());
Handling Unparsed Responses
If the response body cannot be parsed into JavaScript (i.e., it is not in JSON, XML, HTML, CSV, or another parsable format), you can still assert certain aspects of the data.
Test if the response body contains a string:
pm.test("Body contains string",() => {
pm.expect(pm.response.text()).to.include("customer_id");
});
This method won't provide the exact location of the string, as it tests the entire response body. To check if the entire response matches a specific string (usually effective only for short responses)
pm.test("Body is string", function () {
pm.response.to.have.body("whole-body-text");
});
Asserting on HTTP Responses
Your tests can inspect various aspects of the response to a request, including the body, status codes, headers, cookies, response times, and more.
Testing the Response Body
Check for specific values in the response body:
pm.test("Person is Jane", () => {
const responseJson = pm.response.json;
pm.expect(responseJson.name).to.eql("Jane");
pm.expect(responseJson.age).to.eql(23);
});
Testing Status Codes
Test the response status code:
pm.test("Status code is 201", () => {
pm.response.to.have.status(201);
});
If you want to test whether the status code is one of a set, include them all in an array and use oneOf:
pm.test("Successful POST request", () => {
pm.expect(pm.response.code).to.be.oneOf([201, 202]);
});
Check the status code text:
pm.test("Status code name has string", () => {
pm.response.to.have.status("Created");
});
Testing Headers
Check for the presence of a response header:
pm.test("Content-Type header is present", () => {
pm.response.to.have.header("Content-Type");
});
Test for a response header with a specific value:
pm.test("Content-Type header is application/json", () => {
pm.expect(pm.response.headers['Content-Type']).to.eql('application/json');
});
Testing Cookies
Test if a cookie exists in the response:
pm.test("Cookie JSESSIONID is present", () => {
pm.expect(pm.response.cookies['cookie-test1']).to.not.be.undefined;
});
Test a specific cookie value:
pm.test("Cookie isLoggedIn has value 1", () => {
pm.expect(pm.response.cookies['cookie-test1']).to.eql('0');
});
Testing Response Time
Test if the response time is within a specified range:
pm.test("Response time is less than 200ms", () => {
pm.expect(pm.response.responseTime).to.be.below(200);
});
pm.response.to.be.*
pm.response.to.be
is a series of built-in rules for quick assertions.
pm.response.to.be.info
Check if the status code is 1XX
pm.response.to.be.success
Check if the status code is 2XX
pm.response.to.be.redirection
Check if the status code is 3XX
pm.response.to.be.clientError
Check if the status code is 4XX
pm.response.to.be.serverError
Check if the status code is 5XX
pm.response.to.be.error
Check if the status code is 4XX or 5XX
pm.response.to.be.ok
Check if the status code is 200
pm.response.to.be.accepted
Check if the status code is 202
pm.response.to.be.badRequest
Check if the status code is 400
pm.response.to.be.unauthorized
Check if the status code is 401
pm.response.to.be.forbidden
Check if the status code is 403
pm.response.to.be.notFound
Check if the status code is 404
pm.response.to.be.rateLimited
Check if the status code is 429