Writing tests and assertions in scripts
You can add test specifications and assertions to your scripts using the pm.test and pm.expect methods.
pm.test
Use the pm.test method to add test specifications inside your scripts. Tests include a name and assertion function. The scripts available to you depend on the request type:
- For HTTP requests, use Pre-request or Post-response scripts.
- For gRPC requests, use Before invoke, On message, or After response scripts.
- For GraphQL requests, use Before query or After response scripts.
A test looks something like the following, whatever the request type:
Where:
testName- A string that contains the test’s name.specFunction- The function defining the test logic.
Postman outputs test results as part of the response. The pm.test method returns the pm object, enabling you to chain calls.
Examples
The pm.test method works the same way for every request type, but the assertions inside these examples are specific to HTTP requests. For the assertions available to other request types, see Write tests for gRPC requests using JavaScript assertions in Postman and Reference Postman responses in scripts.
Check whether a response is valid to proceed:
Test an asynchronous function using an optional done callback:
Get the total number of tests run from a specific location in code:
Skip a test. The method returns the pm object, so you can chain it:
For an example that groups multiple assertions in a single gRPC test, see Write tests for gRPC requests using JavaScript assertions in Postman.
pm.expect
The pm.expect method enables you to write assertions on your response data using ChaiJS expect BDD syntax.
value- What you want to test, where*can be any type of value, such as a string or integer.Assertion- A Chai Assertion object containing chainable methods.
You can also use pm.response.to.have.* and pm.response.to.be.* to build your assertions.
See Postman test script examples for more assertions.
Examples
Check if the response returns an HTTP 200 OK response:
Check if the request’s response body contains the true value: