# Postman test script examples
Depending on your test logic and how you want to get the results, there are various ways to structure the test assertions in a test script. This page provides post-response script examples for various API testing scenarios in Postman. You can use these post-response scripts in your request to parse response data and make assertions. You can also use these scripts to validate response structure and troubleshoot common test errors.
This section covers some common ways to write assertions, along with a list of examples explaining how to use [pm.\* APIs](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/overview/) to write tests. To try these tests, open a request in Postman, then select the **Scripts > Post-response** tab and enter the JavaScript code for the example.
## Test for a status code
You can use the `statusCode` property available over [pm.response](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-response/) to test the status code of the response.
```js
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
```
This code uses the `pm` library to run the `test` method. The text string will appear in the test output. The function inside the test represents an assertion. In this case, the code uses a `to.have` chain to express the assertion.
This test checks the response code returned by the API. If the response code is `200`, the test will pass, otherwise it will fail.

To learn what test results look like when they pass or fail, change the status code in the assertion code and send the request again.
You can also assert the same using the [pm.expect](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-test-expect/) method.
```js
pm.test("Status code is 200", () => {
pm.expect(pm.response.code).to.eql(200);
});
```
You can use the `pm.response.to.be.ok` as shorthand to test if the status code is 0.
Refer to the [Chai Assertion Library Docs](https://www.chaijs.com/api/bdd/) for a complete overview of assertion syntax options.
### Test response times
Test for the response time to be within a specified range:
```js
pm.test("Response time is less than 200ms", () => {
pm.expect(pm.response.responseTime).to.be.below(200);
// or
pm.response.to.have.responseTime.not.above(200);
// Using pm.expect
pm.expect(pm.response.responseTime).to.be.below(300);
});
```
For requests with streaming methods, `pm.response.responseTime` denotes the total duration for the request's execution.
## Test metadata
To check if response metadata is present:
```javascript
pm.test('"content-type" is present in response metadata', () => {
pm.response.to.have.metadata('content-type');
// Using pm.expect
pm.expect(pm.response.metadata.has('content-type')).to.be.true;
});
```
You can also assert the value of the metadata:
```javascript
pm.test('"content-type" response metadata is "application/grpc"', () => {
pm.response.to.have.metadata('content-type', 'application/grpc');
// Using pm.expect
pm.expect(pm.response.metadata.get('content-type')).to.equal('application/grpc');
});
```
Similar assertions can be written for request metadata using the [pm.request](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-request/) object.
## Testing response trailers
To check if a response trailer is present:
```javascript
pm.test('"grpc-status-details-bin" is present in response trailers', () => {
pm.response.to.have.trailer('grpc-status-details-bin');
// Using pm.expect
pm.expect(pm.response.trailers.has('grpc-status-details-bin')).to.be.true;
});
```
You can also assert the value of the trailer:
```javascript
pm.test('"grpc-status-details-bin" response trailer is "dummy-value"', () => {
pm.response.to.have.trailer('grpc-status-details-bin', 'dummy-value');
// Using pm.expect
pm.expect(pm.response.trailers.get('grpc-status-details-bin')).to.equal('dummy-value');
});
```
## Testing response trailers
To check if a response trailer is present:
```javascript
pm.test('"grpc-status-details-bin" is present in response trailers', () => {
pm.response.to.have.trailer('grpc-status-details-bin');
// Using pm.expect
pm.expect(pm.response.trailers.has('grpc-status-details-bin')).to.be.true;
});
```
You can also assert the value of the trailer:
```javascript
pm.test('"grpc-status-details-bin" response trailer is "dummy-value"', () => {
pm.response.to.have.trailer('grpc-status-details-bin', 'dummy-value');
// Using pm.expect
pm.expect(pm.response.trailers.get('grpc-status-details-bin')).to.equal('dummy-value');
});
```
## Testing responses
For requests with multiple response messages, such as those using a bidirectional streaming method, the tests in this section check all messages for the given assertion. For requests with a single response message, like those using unary or client streaming methods, the assertion is tested only on that message.
Also, when writing assertions using `pm.response.messages.to.*`, you will be asserting on an array of message content and not the complete [pm.response](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-response/) message object.
You can test the assertions in this section on request messages as well using the `pm.request` object.
### Test the existence of a message
To test the existence of a response message (strictly):
```javascript
pm.test('Correct user details are received', () => {
pm.response.to.have.message({
userId: '123',
name: 'John Doe',
email: 'john@example.com',
phone: '+1-555-555-5555',
age: 30,
company: 'XYZ'
});
});
```
### Test for a message with a specific property
You can assert that the given object's properties are a subset of any messages received as a response:
```javascript
pm.test('User details are updated successfully', () => {
pm.response.messages.to.include({
action: 'update-user-details',
status: 'success'
});
});
```
By default, `pm.response.messages.to.include()` has `.deep` applied to it.
### Test for a common property across all messages
To check if a common property exists in all the received messages:
```javascript
pm.test('All users have "company" in their profile', () => {
pm.response.messages.to.have.property('isActive');
});
```
You can also assert the value of a common property:
```javascript
pm.test('All users are in same company', () => {
pm.response.messages.to.have.property('company', 'XYZ');
});
```
By default, `pm.response.messages.to.have.property()` has `.deep` and `.nested` applied to it.
### Test messages against a JSON Schema
You can assert that the received messages match the given JSON Schema:
```javascript
const schema = {
type: "object",
properties: {
username: {
type: "string",
pattern: "^[a-z0-9_-]{3,16}$"
}
}
};
pm.test('All response messages have correct username', () => {
pm.response.messages.to.have.jsonSchema(schema);
});
pm.test('Assert on a specific message', () => {
pm.expect(pm.response.messages.idx(10).data).to.have.jsonSchema(schema);
});
```
## Work with a stream of messages
The examples below show how to work with a stream of messages and write assertions on them.
```javascript
pm.test('Should receive keep-alive message roughly every 5 seconds', () => {
const keepAliveMessage = pm.response.messages.filter({
data: {
type: 'keep-alive'
}
});
for (let i = 1; i < keepAliveMessage.length; i++) {
const time1 = keepAliveMessage[i-1].timestamp;
const time2 = keepAliveMessage[i].timestamp;
pm.expect(time2-time1).to.be.within(4800, 5200);
}
});
```
```javascript
pm.test('Every request message should have a corresponding response message', () => {
pm.request.messages.each((reqMsg) => {
pm.response.messages.to.include({ id: reqMsg.data.id });
});
});
```
## Use multiple assertions
Your tests can include multiple assertions as part of a single test. Use this to group together related assertions:
```js
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 contained assertions fails, the test as a whole will fail. All assertions must be successful for the test to pass.
## Parse response body data
To carry out assertions on your responses, you will first need to parse the data into a JavaScript object that your assertions can use.
To parse JSON data, use the following syntax:
```js
const responseJson = pm.response.json();
```
To parse XML, use the [xml2js](https://www.npmjs.com/package/xml2js) library with the [`require` method](/docs/tests-and-scripts/write-scripts/packages/package-library/#use-external-libraries-in-packages):
```js
var parseString = require('xml2js').parseString;
parseString(pm.response.text(), function (err, result) {
console.log(result);
});
```
If you're working with complex XML responses you may find [Console logging](/docs/sending-requests/response-data/troubleshooting-api-requests/#debugging-in-the-console) useful.
To parse CSV, use the [CSV parse (csv-parse/lib/sync)](https://csv.js.org/parse/) utility:
```js
const parse = require('csv-parse/lib/sync');
const responseJson = parse(pm.response.text());
```
To parse HTML, use [cheerio](https://cheerio.js.org/) with the [`require` method](/docs/tests-and-scripts/write-scripts/packages/package-library/#use-external-libraries-in-packages):
```js
const $ = require('cheerio').load(pm.response.text());
//output the html for testing
console.log($.html());
```
### Handle responses that don't parse
If you can't parse the response body into JavaScript because it's not formatted as JSON, XML, HTML, CSV, or any other parsable data format, you can still make assertions on the data.
Test if the response body has a string:
```js
pm.test("Body contains string",() => {
pm.expect(pm.response.text()).to.include("customer_id");
});
```
This doesn't tell you where the string was encountered because it carries out the test on the whole response body. Test if a response matches a string:
```js
pm.test("Body is string", function () {
pm.response.to.have.body("whole-body-text");
});
```
## Make assertions on the HTTP response
Your tests can check various aspects of a request response, including the [body](#test-response-body), [status codes](#test-status-codes), [headers](#test-headers), [cookies](#test-cookies), [response times](#test-response-times), and more.
### Test response body
Check for particular values in the response body:
```js
/* Response has the following structure:
{
"name": "Jane",
"age": 23
},
*/
pm.test("Person is Jane", () => {
const responseJson = pm.response.json();
pm.expect(responseJson.name).to.eql("Jane");
pm.expect(responseJson.age).to.eql(23);
});
```
### Test status codes
Test for the response status code:
```js
pm.test("Status code is 201", () => {
pm.response.to.have.status(201);
});
```
If you want to test for the status code being one of a set, include them all in an array and use `oneOf`:
```js
pm.test("Successful POST request", () => {
pm.expect(pm.response.code).to.be.oneOf([201,202]);
});
```
Check the status code text:
```js
pm.test("Status code name has string", () => {
pm.response.to.have.status("Created");
});
```
### Test headers
Check that a response header is present:
```js
pm.test("Content-Type header is present", () => {
pm.response.to.have.header("Content-Type");
});
```
Test for a response header having a particular value:
```js
pm.test("Content-Type header is application/json", () => {
pm.expect(pm.response.headers.get('Content-Type')).to.include('application/json');
});
```
### Test cookies
Test if a cookie is present in the response:
```js
pm.test("Cookie isLoggedIn is present", () => {
pm.expect(pm.cookies.has('isLoggedIn')).to.be.true;
});
```
Test for a particular cookie value:
```js
pm.test("Cookie isLoggedIn has value 1", () => {
pm.expect(pm.cookies.get('isLoggedIn')).to.eql('1');
});
```
## Common assertion examples
The following examples of common assertions might help you write your post-response scripts.
For a more comprehensive overview of what you can include in your assertions, refer to the [Chai Assertion Library Docs](https://www.chaijs.com/api/bdd/).
### Assert a response value against a variable
Check if a response property has the same value as a variable (this example uses an environment variable):
```js
pm.test("Response property matches environment variable", function () {
pm.expect(pm.response.json().name).to.eql(pm.environment.get("name"));
});
```
See [Using variables](/docs/sending-requests/variables/variables/) to learn more about using variables in your post-response scripts.
### Assert a value type
Test the type of any part of the response:
```js
/* Response has the following structure:
{
"name": "Jane",
"age": 29,
"hobbies": [
"skating",
"painting"
],
"email": null
},
*/
const jsonData = pm.response.json();
pm.test("Test data type of the response", () => {
pm.expect(jsonData).to.be.an("object");
pm.expect(jsonData.name).to.be.a("string");
pm.expect(jsonData.age).to.be.a("number");
pm.expect(jsonData.hobbies).to.be.an("array");
pm.expect(jsonData.website).to.be.undefined;
pm.expect(jsonData.email).to.be.null;
});
```
### Assert array properties
Check if an array is empty, and if it has particular items:
```js
/* Response has the following structure:
{
"errors": [],
"areas": [ "goods", "services" ],
"settings": [
{
"type": "notification",
"detail": [ "email", "sms" ]
},
{
"type": "visual",
"detail": [ "light", "large" ]
}
]
},
*/
const jsonData = pm.response.json();
pm.test("Test array properties", () => {
//errors array is empty
pm.expect(jsonData.errors).to.be.empty;
//areas array includes "goods"
pm.expect(jsonData.areas).to.include("goods");
//get the notification settings object
const notificationSettings = jsonData.settings.find
(m => m.type === "notification");
pm.expect(notificationSettings)
.to.be.an("object", "Could not find the setting");
//detail array must include "sms"
pm.expect(notificationSettings.detail).to.include("sms");
//detail array must include all listed
pm.expect(notificationSettings.detail)
.to.have.members(["email", "sms"]);
});
```
The order in `.members` doesn't affect the test.
### Assert object properties
Assert that an object has keys or properties:
```js
/* Response has the following structure:
{
"a": 1,
"b": 2
},
*/
pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b');
pm.expect({a: 1, b: 2}).to.have.any.keys('a', 'b');
pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd');
pm.expect({a: 1}).to.have.property('a');
pm.expect({a: 1, b: 2}).to.be.a('object')
.that.has.all.keys('a', 'b');
```
Target can be an `object`, `set`, `array` or `map`. If `.keys` is run without `.all` or `.any`, the expression defaults to `.all`. As `.keys` behavior varies based on the target `type`, it's recommended to check the `type` before using `.keys` with `.a`.
### Assert that a value is in a set
Check a response value against a list of valid options:
```js
/* Response has the following structure:
{
"type": "Subscriber"
},
*/
pm.test("Value is in valid list", () => {
pm.expect(pm.response.json().type)
.to.be.oneOf(["Subscriber", "Customer", "User"]);
});
```
### Assert that an object is contained
Check that an object is part of a parent object:
```js
/* Response has the following structure:
{
"id": "d8893057-3e91-4cdd-a36f-a0af460b6373",
"created": true,
"errors": []
},
*/
pm.test("Object is contained", () => {
const expectedObject = {
"created": true,
"errors": []
};
pm.expect(pm.response.json()).to.deep.include(expectedObject);
});
```
The `.deep` assertion causes all `.equal`, `.include`, `.members`, `.keys`, and `.property` assertions that follow in the chain to use deep equality instead of strict (`===`) equality.
### Assert the current environment
Check the [active environment](/docs/sending-requests/variables/managing-environments/#switch-between-environments) in Postman:
```js
pm.test("Check the active environment", () => {
pm.expect(pm.environment.name).to.eql("Production");
});
```