How to Use Tests Tab in Postman for API Testing
In Postman, the
Tests tab lets you write JavaScript code to check API response data after a request runs. You add assertions there to verify status codes, response times, or data values, helping automate API testing easily.Syntax
The Tests tab uses JavaScript to write test scripts that run after the API response is received. You use pm object methods like pm.response.to.have.status(code) to check the response status, or pm.expect() for assertions.
Key parts:
pm.response: Access the API response.pm.expect(): Assertion function to check values.tests["Test Name"] = true/false: Legacy way to name tests (optional).
javascript
pm.test("Status code is 200", () => { pm.response.to.have.status(200); }); pm.test("Response time is less than 500ms", () => { pm.expect(pm.response.responseTime).to.be.below(500); });
Example
This example shows how to test that the API returns status 200 and that the JSON response has a key success set to true.
javascript
pm.test("Status code is 200", () => { pm.response.to.have.status(200); }); pm.test("Response has success true", () => { const jsonData = pm.response.json(); pm.expect(jsonData.success).to.eql(true); });
Output
PASS: Status code is 200
PASS: Response has success true
Common Pitfalls
Common mistakes include:
- Not parsing JSON response before accessing data (use
pm.response.json()). - Using incorrect assertion syntax or forgetting arrow functions.
- Writing tests that depend on dynamic data without proper checks.
- Confusing
pm.expect()withassertor other libraries.
Always check the response format and write clear, simple assertions.
javascript
/* Wrong: Accessing JSON without parsing */ pm.test("Check user id", () => { pm.expect(pm.response.user.id).to.eql(123); // Error: pm.response.user undefined }); /* Right: Parse JSON first */ pm.test("Check user id", () => { const data = pm.response.json(); pm.expect(data.user.id).to.eql(123); });
Quick Reference
| Feature | Usage Example | Description |
|---|---|---|
| Check status code | pm.response.to.have.status(200); | Verifies HTTP status code is 200 |
| Check response time | pm.expect(pm.response.responseTime).to.be.below(500); | Ensures response time is under 500ms |
| Parse JSON | const data = pm.response.json(); | Extracts JSON body from response |
| Check JSON value | pm.expect(data.key).to.eql(value); | Asserts JSON key equals expected value |
| Write test block | pm.test("Test name", () => { /* assertions */ }); | Defines a named test with assertions |
Key Takeaways
Use the Tests tab to write JavaScript assertions that run after each API request.
Always parse JSON responses with pm.response.json() before checking data.
Use pm.test() blocks with pm.expect() for clear, readable tests.
Check status codes, response times, and response data to validate APIs.
Avoid common mistakes like accessing response data without parsing or wrong assertion syntax.