How to test your Postman collections using scripts and assertions

This blog will teach you how to test your Postman collections using scripts and assertions. You will learn how to write and run tests for your requests and collections using Postman.

1. Introduction

Postman is a popular tool for API development and testing. It allows you to create, send, and manage HTTP requests and responses, as well as organize them into collections. But how do you ensure that your requests and collections are working as expected? How do you verify that your API is returning the correct data and status codes? How do you automate your testing process and generate reports?

The answer is to use Postman scripts and assertions. Postman scripts are snippets of JavaScript code that you can write and execute before or after your requests. Postman assertions are statements that check if a certain condition is true or false. By using Postman scripts and assertions, you can write and run tests for your requests and collections, and validate the functionality and performance of your API.

In this tutorial, you will learn how to test your Postman collections using scripts and assertions. You will learn how to:

  • Write tests for your requests using Postman scripts and assertions
  • Run tests for your requests using Postman
  • Write tests for your collections using Postman scripts and assertions
  • Run tests for your collections using Postman
  • Follow best practices for testing your Postman collections

By the end of this tutorial, you will be able to test your Postman collections using scripts and assertions, and improve the quality and reliability of your API.

Ready to get started? Let’s begin!

2. What are Postman scripts and assertions?

In this section, you will learn what are Postman scripts and assertions, and how they can help you test your Postman collections. You will also learn about the different types of scripts and assertions that Postman supports, and how to write them using the Postman scripting language.

Postman scripts are snippets of JavaScript code that you can write and execute before or after your requests. You can use Postman scripts to perform various tasks, such as:

  • Setting or updating variables
  • Logging data to the console
  • Modifying request or response data
  • Writing and running tests

Postman assertions are statements that check if a certain condition is true or false. You can use Postman assertions to validate various aspects of your requests and responses, such as:

  • Status codes
  • Headers
  • Bodies
  • JSON schemas
  • Response times

Postman supports two types of scripts: pre-request scripts and test scripts. Pre-request scripts are executed before your request is sent, and can be used to prepare your request data, set variables, or generate dynamic parameters. Test scripts are executed after your request is received, and can be used to verify your response data, set variables, or generate reports.

Postman supports two types of assertions: Chai assertions and Postman assertions. Chai assertions are based on the Chai assertion library, which provides a rich set of methods and expressions to write readable and fluent tests. Postman assertions are based on the pm.expect method, which is a wrapper around the Chai assertion library, and provides some additional features and syntax options.

To write Postman scripts and assertions, you need to use the Postman scripting language, which is a subset of JavaScript that runs in a sandboxed environment. The Postman scripting language provides access to various built-in libraries and objects, such as:

  • pm: The pm object is the main object that you use to access the Postman sandbox features, such as variables, requests, responses, tests, and assertions.
  • console: The console object is used to log data to the Postman console, which is a separate window that displays the output of your scripts.
  • lodash: The lodash object is a reference to the lodash library, which provides a collection of utility functions for manipulating arrays, objects, strings, and other data types.
  • CryptoJS: The CryptoJS object is a reference to the CryptoJS library, which provides a collection of cryptographic algorithms and functions for encrypting and decrypting data.
  • xml2Json: The xml2Json function is used to convert XML data to JSON data, which is easier to manipulate and validate in Postman.

Now that you have a basic understanding of what are Postman scripts and assertions, let’s see how to write and run tests for your requests and collections using them.

2.1. Postman scripts

Postman scripts are snippets of JavaScript code that you can write and execute before or after your requests. You can use Postman scripts to perform various tasks, such as setting or updating variables, logging data to the console, modifying request or response data, and writing and running tests.

To write a Postman script, you need to open the Scripts tab in the request editor, and select either Pre-request Script or Tests from the dropdown menu. You will see a code editor where you can write your script using the Postman scripting language.

Here is an example of a pre-request script that generates a random number and sets it as a variable:

// Generate a random number between 1 and 100
var randomNumber = Math.floor(Math.random() * 100) + 1;

// Set the randomNumber variable
pm.variables.set("randomNumber", randomNumber);

Here is an example of a test script that checks if the response status code is 200 and the response body contains a specific string:

// Check if the status code is 200
pm.test("Status code is 200", function () {
  pm.response.to.have.status(200);
});

// Check if the response body contains "Hello World"
pm.test("Body contains Hello World", function () {
  pm.expect(pm.response.text()).to.include("Hello World");
});

You can run your Postman scripts by sending your request. You will see the output of your scripts in the Test Results tab and the Postman Console window. You can also use the Send and Download option to save the response data to a file.

Postman scripts are a powerful way to enhance and automate your Postman collections. You can use them to write and run tests for your requests and collections, and validate the functionality and performance of your API.

2.2. Postman assertions

Postman assertions are statements that check if a certain condition is true or false. You can use Postman assertions to validate various aspects of your requests and responses, such as status codes, headers, bodies, JSON schemas, response times, and more.

To write a Postman assertion, you need to use the pm.expect method, which is a wrapper around the Chai assertion library. The pm.expect method takes an actual value as an argument, and returns an object that has various methods and properties to perform different types of assertions. You can chain multiple methods and properties to create complex and expressive assertions.

Here is an example of a Postman assertion that checks if the response status code is 200:

// Check if the status code is 200
pm.test("Status code is 200", function () {
  pm.expect(pm.response.code).to.equal(200);
});

Here is an example of a Postman assertion that checks if the response body matches a JSON schema:

// Define the JSON schema
var schema = {
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "number"
    },
    "hobbies": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  },
  "required": ["name", "age", "hobbies"]
};

// Check if the response body matches the schema
pm.test("Body matches schema", function () {
  pm.expect(pm.response.json()).to.be.jsonSchema(schema);
});

You can write multiple Postman assertions in a test script, and use the pm.test method to group them into logical units. The pm.test method takes a name and a function as arguments, and executes the function as a test. You can use the name to describe what the test is checking, and the function to write the assertions. The pm.test method also returns a boolean value indicating whether the test passed or failed.

Postman assertions are a powerful way to verify and validate your Postman collections. You can use them to write and run tests for your requests and collections, and ensure that your API is returning the correct data and status codes.

3. How to write tests for your requests using Postman scripts and assertions

In this section, you will learn how to write tests for your requests using Postman scripts and assertions. You will learn how to use the Postman scripting language to write different types of assertions, and how to organize your tests using the pm.test method.

To write tests for your requests, you need to follow these steps:

  1. Open the request that you want to test in the Postman app.
  2. Click on the Scripts tab in the request editor, and select Tests from the dropdown menu.
  3. Write your test script using the Postman scripting language and the pm.expect method.
  4. Optionally, group your assertions into logical units using the pm.test method.
  5. Save your request and send it to run your test script.

Let’s see an example of how to write tests for a simple GET request that returns a JSON response. The request URL is https://jsonplaceholder.typicode.com/users/1, and the response body is:

{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}

We want to test the following aspects of the request and response:

  • The status code is 200
  • The response time is less than 200 ms
  • The response body is a valid JSON object
  • The response body has the expected properties and values

Here is how we can write the test script for this request:

// Check if the status code is 200
pm.test("Status code is 200", function () {
  pm.expect(pm.response.code).to.equal(200);
});

// Check if the response time is less than 200 ms
pm.test("Response time is less than 200 ms", function () {
  pm.expect(pm.response.responseTime).to.be.below(200);
});

// Check if the response body is a valid JSON object
pm.test("Response body is a valid JSON object", function () {
  pm.response.to.be.json;
});

// Check if the response body has the expected properties and values
pm.test("Response body has the expected properties and values", function () {
  var jsonData = pm.response.json();
  pm.expect(jsonData.id).to.equal(1);
  pm.expect(jsonData.name).to.equal("Leanne Graham");
  pm.expect(jsonData.username).to.equal("Bret");
  pm.expect(jsonData.email).to.equal("Sincere@april.biz");
  pm.expect(jsonData.address.street).to.equal("Kulas Light");
  pm.expect(jsonData.address.suite).to.equal("Apt. 556");
  pm.expect(jsonData.address.city).to.equal("Gwenborough");
  pm.expect(jsonData.address.zipcode).to.equal("92998-3874");
  pm.expect(jsonData.address.geo.lat).to.equal("-37.3159");
  pm.expect(jsonData.address.geo.lng).to.equal("81.1496");
  pm.expect(jsonData.phone).to.equal("1-770-736-8031 x56442");
  pm.expect(jsonData.website).to.equal("hildegard.org");
  pm.expect(jsonData.company.name).to.equal("Romaguera-Crona");
  pm.expect(jsonData.company.catchPhrase).to.equal("Multi-layered client-server neural-net");
  pm.expect(jsonData.company.bs).to.equal("harness real-time e-markets");
});

As you can see, we have used the pm.test method to group our assertions into four logical units, and given them descriptive names. We have also used the pm.expect method to write different types of assertions, such as equality, comparison, inclusion, and validity. We have used the pm.response object to access the response data, and the pm.response.json() method to parse the response body as a JSON object.

By writing tests for your requests using Postman scripts and assertions, you can ensure that your requests and responses are working as expected, and that your API is returning the correct data and status codes.

4. How to run tests for your requests using Postman

In this section, you will learn how to run tests for your requests using Postman. You will learn how to use the Postman app to send your requests and view the test results, and how to use the Postman Collection Runner to run multiple requests and tests in a sequence.

To run tests for your requests, you need to follow these steps:

  1. Open the request that you want to test in the Postman app.
  2. Make sure that you have written your test script in the Scripts tab and selected Tests from the dropdown menu.
  3. Click on the Send button to send your request and run your test script.
  4. Click on the Test Results tab to view the test results. You will see the name and status of each test, and the number of passed and failed tests.
  5. Optionally, click on the Console icon to open the Postman Console window. You will see the output of your test script, such as console logs, errors, and warnings.

You can also use the Postman Collection Runner to run multiple requests and tests in a sequence. The Postman Collection Runner is a tool that allows you to run a collection of requests and tests with different settings and options, such as iterations, data files, delays, and environment variables. You can use the Postman Collection Runner to automate your testing process and generate reports.

To use the Postman Collection Runner, you need to follow these steps:

  1. Click on the Runner icon in the Postman app to open the Postman Collection Runner window.
  2. Select the collection that you want to run from the Collection dropdown menu.
  3. Optionally, select the environment that you want to use from the Environment dropdown menu.
  4. Optionally, adjust the settings and options for your collection run, such as iterations, data files, delays, and log level.
  5. Click on the Run button to start your collection run.
  6. View the collection run results in the Run Results tab. You will see the name and status of each request and test, and the number of passed and failed tests.
  7. Optionally, export the collection run results as a JSON or HTML file.

By running tests for your requests using Postman, you can verify and validate your Postman collections, and ensure that your requests and responses are working as expected, and that your API is returning the correct data and status codes.

5. How to write tests for your collections using Postman scripts and assertions

In this section, you will learn how to write tests for your collections using Postman scripts and assertions. You will learn how to use the Postman scripting language to write different types of assertions, and how to apply them to your entire collection or a specific folder.

To write tests for your collections, you need to follow these steps:

  1. Open the collection that you want to test in the Postman app.
  2. Click on the Edit icon next to the collection name to open the collection editor.
  3. Click on the Tests tab in the collection editor.
  4. Write your test script using the Postman scripting language and the pm.expect method.
  5. Optionally, group your assertions into logical units using the pm.test method.
  6. Save your collection and close the collection editor.

By writing tests in the collection level, you can apply them to your entire collection or a specific folder. This means that the tests will run for every request in the collection or the folder, and you don’t have to write them for each request individually. This can save you time and effort, and make your tests more consistent and maintainable.

Let’s see an example of how to write tests for a collection that contains the request that we wrote tests for in the previous sections. The collection name is Test Postman Collection, and the request name is Get User. The request URL is https://jsonplaceholder.typicode.com/users/1, and the response body is the same as before.

We want to test the following aspects of the request and response for every request in the collection:

  • The status code is 200
  • The response time is less than 200 ms
  • The response body is a valid JSON object

Here is how we can write the test script for the collection:

// Check if the status code is 200
pm.test("Status code is 200", function () {
  pm.expect(pm.response.code).to.equal(200);
});

// Check if the response time is less than 200 ms
pm.test("Response time is less than 200 ms", function () {
  pm.expect(pm.response.responseTime).to.be.below(200);
});

// Check if the response body is a valid JSON object
pm.test("Response body is a valid JSON object", function () {
  pm.response.to.be.json;
});

As you can see, we have written the same tests that we wrote for the request level, but this time in the collection level. This means that these tests will run for every request in the collection, and we don’t have to repeat them for each request.

By writing tests for your collections using Postman scripts and assertions, you can ensure that your collections are working as expected, and that your API is returning the correct data and status codes for every request.

6. How to run tests for your collections using Postman

In this section, you will learn how to run tests for your collections using Postman. You will learn how to use the Postman app to send your requests and view the test results, and how to use the Postman Collection Runner to run multiple requests and tests in a sequence.

To run tests for your collections, you need to follow these steps:

  1. Open the collection that you want to test in the Postman app.
  2. Click on the Runner icon in the Postman app to open the Postman Collection Runner window.
  3. Select the collection that you want to run from the Collection dropdown menu.
  4. Optionally, select the environment that you want to use from the Environment dropdown menu.
  5. Optionally, adjust the settings and options for your collection run, such as iterations, data files, delays, and log level.
  6. Click on the Run button to start your collection run.
  7. View the collection run results in the Run Results tab. You will see the name and status of each request and test, and the number of passed and failed tests.
  8. Optionally, export the collection run results as a JSON or HTML file.

By running tests for your collections using Postman, you can verify and validate your Postman collections, and ensure that your requests and responses are working as expected, and that your API is returning the correct data and status codes for every request.

7. Best practices for testing your Postman collections

In this section, you will learn some best practices for testing your Postman collections using scripts and assertions. You will learn how to write effective and maintainable tests, and how to avoid common pitfalls and errors.

Here are some best practices for testing your Postman collections:

  • Use descriptive and meaningful names for your tests and assertions. This will help you and others to understand the purpose and scope of your tests, and to identify and troubleshoot any failures.
  • Use the pm.test method to group your assertions into logical units. This will help you to organize your tests and to report the results in a clear and structured way.
  • Use the pm.expect method to write different types of assertions, such as equality, comparison, inclusion, and validity. This will help you to validate various aspects of your requests and responses, and to write readable and fluent tests.
  • Use the pm.response object to access the response data, such as status code, headers, body, and response time. This will help you to write tests that are based on the actual response data, and not on assumptions or hard-coded values.
  • Use the pm.response.json() method to parse the response body as a JSON object. This will help you to manipulate and validate the response data more easily and efficiently.
  • Use the pm.variables object to set and get variables in your scripts. This will help you to store and reuse data across your requests and tests, and to avoid duplication and inconsistency.
  • Use the console object to log data to the Postman Console. This will help you to debug your scripts and to view the output of your tests.
  • Use the built-in libraries and objects that Postman provides, such as lodash, CryptoJS, and xml2Json. This will help you to perform various tasks and functions in your scripts, such as manipulating data, encrypting and decrypting data, and converting data formats.
  • Use comments to document your scripts and explain your logic. This will help you and others to understand and maintain your scripts, and to avoid confusion and errors.
  • Use the Postman Collection Runner to run multiple requests and tests in a sequence. This will help you to automate your testing process and to generate reports.

By following these best practices, you can write effective and maintainable tests for your Postman collections, and ensure that your requests and responses are working as expected, and that your API is returning the correct data and status codes.

8. Conclusion

In this tutorial, you have learned how to test your Postman collections using scripts and assertions. You have learned how to:

  • Write tests for your requests using Postman scripts and assertions
  • Run tests for your requests using Postman
  • Write tests for your collections using Postman scripts and assertions
  • Run tests for your collections using Postman
  • Follow best practices for testing your Postman collections

By testing your Postman collections using scripts and assertions, you can ensure that your requests and responses are working as expected, and that your API is returning the correct data and status codes. You can also automate your testing process and generate reports.

Postman is a powerful tool for API development and testing. It allows you to create, send, and manage HTTP requests and responses, as well as organize them into collections. By using Postman scripts and assertions, you can write and run tests for your requests and collections, and validate the functionality and performance of your API.

We hope that this tutorial has been helpful and informative for you. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading and happy testing!

Leave a Reply

Your email address will not be published. Required fields are marked *