You can use post-response scripts in Postman to run JavaScript after a request runs. By including code in theScripts > 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.
Some of the most common approaches toAPI 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 thePost-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.
ThePre-request andPost-response tabs use the Postman Sandbox, a runtime based on Node.js that enables you to add dynamic behavior to requests and collections.
TheScripts > 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, seeWrite pre-request scripts to add dynamic behavior in Postman.
TheScripts > Post-response tab provides for any post-processing after a request is sent and includes the ability to write tests for assessing response data. ThePost-response tab has theChai.js library built in, so you can use Chai’s behavior-driven development (BDD) syntax to create readable test assertions.
SelectSnippets at the lower right of the code editor to view a list of test snippets. You can search for and select snippets to inject 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 towrite tests for you.
You can add tests torequests,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 theScripts > Post-response tab. You can write your own JavaScript. You can also selectSnippets at the lower right of the code editor and select a snippet. To make your code more readable, you can select
Beautify in the lower right of the code editor.
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’sTest Results tab.
In theTest Results tab, you can clickRefresh results in the upper right of the response pane to refresh your test results. This gives you the option to refresh your test results without re-sending the request.
Your scripts can include as many tests as you need and will be saved along with the request details when you selectSave. If you share a collection, publish documentation, or use theRun in Postman button, your test code will be included for anyone who views or imports your collection.
You can add tests to a gRPC request before invoke, when the client receives a message, or after response. All 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:
When you selectInvoke, tests run before, during, or after the request is invoked. Once you invoke your gRPC request, updates to scripts in theOn message tab won’t take effect until the next time you invoke the request. If you selectCancel, the request and any further script runs are stopped.
If there are any errors in yourBefore invoke script, the request will stop.
To validate the data returned by a request, you can use thepm.response
object in a test. Define tests using thepm.test
function. Provide a name and function that returns a boolean (true
orfalse
) value to indicate if the test passed or failed. Use Chai.js BDD syntax andpm.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 thePost-response tab of a request to test if the response status code is200
:
pm.test("Status test",function(){ pm.response.to.have.status(200);});
SelectSend to run your request, then select theTest Results tab in the response. The tab header displays how many tests passed and how many ran in total. You can also select theFilter Results dropdown list to view the test results by type:Passed,Skipped, andFailed.
If the request returned a200
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.
Using thepm.expect
syntax gives your test result messages a different format. Experiment with the options to get the output you find most useful.
Fork theIntro 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 requestenvironment, 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;});
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 run order for each request will be collection tests, folder tests and then request tests.
You can alsostore 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 internal 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 theScripts > Post-response tab.
When yourun 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.
You can write scripts to control the order in which your requests run usingbranching and looping.
You can use Postman’s AI assistantPostbot to write tests for your requests. Tell Postbot what to do in natural language, and Postbot generates 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 tests with Postbot, do the following:
Open a request and selectSend so it has a response.
Select theScripts > Post response tab.
(Optional) Select code you’d like Postbot to help with.
SelectOpen Postbot in the code editor. You can also selectControl+Option+P orCtrl+Alt+P to open Postbot.
Tell Postbot what you want to do and selectEnter.
You can also work with Postbot in the following ways:
Postbot can offer suggestions based on your request and the response data. Select the down arrow (↓) on your keyboard and select one of Postbot’s suggestions.
Postbot understands context. Select part of a script or the response body, then tell Postbot what you want to do or change based on the selection.
You can also select part of a JSON response, right-click, then selectUse Postbot. You can tell Postman to generate tests based on the selection. For example, go to a response, select a property, and ask Postbot to generate a test to verify that it exists. Or select specific values in a response and ask Postbot to visualize only that data.
Postbot also powers autocomplete in the post-response script editor. If you’veenabled Postbot, you’ll see code suggestions as you type. Select theTab key to accept the suggestion. If you’ve already paid for Postbot, you get unlimited suggestions and acceptances. For everyone else, feature usage is capped at 200 suggestion acceptance events per month.
To learn more about what you can do with Postbot, go toAbout Postbot.
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 officialJSDoc documentation to learn how to add documentation to your post-response scripts.
The following example has documentation for thelogger
function using JSDoc. The documentation explains what the function does, and defines what thedata
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. */functionlogger(data){ console.log(`Logging information to the console,${data}`)}
If you’re having trouble with your tests, do the following:
After writing your first tests in Postman, you can write more complex tests and use them with other Postman tools.
pm
object, check out some post-response scriptexamples and visit thePostman JavaScript reference.Last modified: 2024/08/24
Explore ready-to-use Collection Templates, build API-first workflows with Postman Flows, and more!