Write scripts to test API response data in Postman

You can use post-response scripts in Postman to run JavaScript after a request runs. By including code in the Scripts > Post-response tab for a request, collection, or folder, you can write and validate API tests. You can also use post-response scripts for debugging your tests.

The Tests tab was renamed to the Post-response tab. If you're an existing Postman user, you can select the Tests tab in an HTTP collection or request, then Postman will redirect you to the Post-response tab. Going forward, the Tests tab will no longer be available, and you can write your tests in the Post-response tab.

Testing in Postman

Some of the most common approaches to API testing are contract testing, unit testing, end-to-end testing, and load testing. Tests confirm that your API is working as expected, that integrations between services function reliably, and that any changes haven't broken existing functionality.

You can write tests for your Postman API requests in JavaScript in the Post-response tab. You can also use test code to aid the debugging process when something goes wrong with your API project. For example, you might write a test to validate your API's error handling by sending a request with incomplete data or wrong parameters.

The Pre-request and Post-response tabs use the Postman Sandbox, a runtime based on Node.js that enables you to add dynamic behavior to requests and collections.

  • The Scripts > Pre-request tab enables you to do any processing needed before sending a request, like setting variable values. Any code here runs before the request is sent. To learn more, see Write pre-request scripts to add dynamic behavior in Postman.

  • The Scripts > Post-response tab provides for any post-processing after a request is sent and includes the ability to write tests for assessing response data. The Post-response tab has the Chai.js library built in, so you can use Chai's behavior-driven development (BDD) syntax to create readable test assertions.

Open the side pane next to the code editor to view a list of test snippets. You can select one or more snippets to inject these pre-written blocks of code. Some will help you retrieve data from variables, some are boilerplate tests, and some perform common utility functions. You can also ask Postman's AI assistant Postbot to write tests for you.

Not sure where to start with testing? Postman provides templates you can use to help test your API's quality, functionality, and performance.

Add a post-response test

You can add tests to requests, collections, and folders in a collection. Postman includes code snippets you add and then change to suit your test logic.

To add a test, open the request, collection, or folder and enter your code in the Scripts > Post-response tab. You can write your own JavaScript or open the side pane next to the code editor and select a snippet.

Post-response scripts can use dynamic variables, carry out test assertions on response data, and pass data between requests. Tests run after the request runs and a response is received from the API. The output appears in the response's Test Results tab.

Request Test Tab

Your scripts can include as many tests as you need and will be saved along with the request details when you select Save icon Save. If you share a collection, publish documentation, or use the Run in Postman button, your test code will be included for anyone who views or imports your collection.

Collections icon See how to work with the Postman basic test syntax to test a single HTTP API request in a sample collection template. To try out this template, select API testing basics.

Add a test to a gRPC request

You can add tests to a gRPC request before invoke or after response. Both execution hooks are available for all gRPC requests regardless of the method type (unary, client streaming, server streaming, or bidirectional streaming).

To add a test to a gRPC request, do the following:

  1. Go to the Scripts tab in your gRPC request.
  2. Select the execution hook (Before invoke or After response) you want to add a test to.
  3. Use snippets from the right pane to add a test, or write custom assertions.

Tests run when you select Invoke, either before or after the request is invoked. If you select Cancel, the request execution and any further script execution are stopped.

If there are any errors in your Before invoke script, the request execution will stop.

Validate responses

To validate the data returned by a request, you can use the pm.response object in a test. Define tests using the pm.test function. Provide a name and function that returns a boolean (true or false) value to indicate if the test passed or failed. Use Chai.js BDD syntax and pm.expect in your assertions to test the response detail.

The first parameter for the .test function is a text string that appears in the test result output. Use this to identify your tests and communicate the purpose of a test to anyone viewing the results.

For example, enter the following in the Post-response tab of a request to test if the response status code is 200:

pm.test("Status test", function () {
    pm.response.to.have.status(200);
});

Select Send to run your request, then select the Test Results tab in the response. The tab header displays how many tests passed and how many ran in total. You can also view the number of Passed, Skipped, and Failed tests.

If the request returned a 200 status code, the test passes. To find out what happens with a different status code, change the expected status code in your post-response script and run the request again.

Format test result messages using pm.expect

Using the pm.expect syntax gives your test result messages a different format. Experiment with the options to get the output you find most useful.

Fork the Intro to writing tests collection to import templates containing some example post-response scripts into Postman and experiment with the code.

Your code can test the request environment, as in the following example:

pm.test("environment to be production", function () {
    pm.expect(pm.environment.get("env")).to.equal("production");
});

You can use different syntax variations to write your tests in a way that you find readable, and that suits your application and testing logic. For example:

pm.test("response should be okay to process", function () {
    pm.response.to.not.be.error;
    pm.response.to.have.jsonBody("");
    pm.response.to.not.have.jsonBody("error");
});

Your tests can validate request responses using syntax that you tailor to the response data format. For example:

pm.test("response must be valid and have a body", function () {
     pm.response.to.be.ok;
     pm.response.to.be.withBody;
     pm.response.to.be.json;
});

Test collections and folders

You can add post-response scripts to a collection, a folder, or a single request within a collection. A post-response script associated with a collection will run after every request in the collection. A post-response script associated with a folder will run after every direct child request in the folder. This enables you to reuse commonly run tests after requests. The execution order for each request will be collection tests, folder tests and then request tests.

You can also store post-response scripts in the Package Library. This enables you to maintain commonly used scripts and tests in a single location, share them with your team, and reuse them in your workspaces.

Adding scripts to collections and folders enables you to test the workflows in your API project. This helps to ensure that your requests cover typical scenarios, providing a reliable experience for application users.

To add or edit collection and folder tests, select a collection or folder in the sidebar, then select the Scripts > Post-response tab.

When you run a collection, the collection runner displays the results for all tests. The test results include the response time in milliseconds and details about whether a specific request in the collection passed or failed its tests.

Collection Tests

You can write scripts to control the order in which your requests run using branching and looping.

Write tests using Postbot

Postman's AI assistant Postbot reduces the need to write boilerplate code for tests. Access Postbot from the Postman footer or the Postbot icon Postbot icon in the code editor. As you start typing your tests, you get suggestions of common behaviors you can test for. Postbot also examines the response to your request and any saved examples to generate relevant test code.

You can use plain language to tell Postbot what to do, and Postman uses artificial intelligence to generate post-response scripts for you. Use Postbot to add a new set of tests, visualize responses, save a field from a response, or fix your existing tests.

To write a test with Postbot, do the following:

  1. Send your request so it has a response.
  2. Select the Scripts > Post response tab.
  3. Select the Postbot icon Postbot icon in the code editor.
  4. Select one of the suggested queries. You can also enter a query to tell Postbot what you need and then select the play button. Postman will write the test for you.
Postbot writing a test

You can also use Postbot to autocomplete test code. If you have a response available and type pm.test, Postbot suggests tests for your request. Select a test name, and Postbot inserts the code to validate your response.

To learn more about what Postbot can do, go to About Postbot.

Add documentation to post-response scripts

Postman supports JSDoc for documenting JavaScript functions in your post-response scripts. Documentation added to your functions using JSDoc will display in a popup window when you call your functions. You can use the official JSDoc documentation to learn how to add documentation to your post-response scripts.

The following example has documentation for the logger function using JSDoc. The documentation explains what the function does, and defines what the data parameter is used for and that it accepts a string data type.

/**
 * This function prints a string to the Postman Console.
 * @param {string} data - The text to print to the Postman Console.
 */
function logger (data) {
    console.log(`Logging information to the console, ${data}`)
}

Debug your tests

If you're having trouble with your tests, do the following:

  • Check if there are any errors in your scripts. A red underline will highlight possible errors. Hover over the error and select View Problem to get help. You can also check the response viewer for specific errors.
  • Debug your tests using log statements to ensure that you are asserting on correct data.

Next steps

After writing your first tests in Postman, you can write more complex tests and use them with other Postman tools.

Last modified: 2024/08/24