How to Write Tests in Postman: Simple Guide for Beginners
In Postman, you write tests using JavaScript inside the
Tests tab of a request. Use pm.test() to define a test with a name and a function containing assertions like pm.response.to.have.status(200) to check the response status.Syntax
Postman tests use JavaScript functions inside the Tests tab. The main function is pm.test(name, function), where name is a string describing the test, and function contains assertions to check the response.
Common assertions include:
pm.response.to.have.status(code)- checks HTTP status codepm.response.to.be.json()- checks if response is JSONpm.expect(value).to.eql(expected)- compares values
javascript
pm.test('Status code is 200', () => { pm.response.to.have.status(200); });
Example
This example tests that the response status is 200 and the JSON body contains 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
Test Results:
โ Status code is 200
โ Response has success true
Common Pitfalls
Common mistakes when writing tests in Postman include:
- Not parsing JSON response before accessing its properties (use
pm.response.json()). - Using incorrect assertion syntax or missing parentheses.
- Writing tests outside the
Teststab or in the wrong place. - Assuming response structure without checking it first.
Always check the response format and use proper assertions.
javascript
/* Wrong: Accessing JSON without parsing */ pm.test('Check success', () => { pm.expect(pm.response.success).to.eql(true); // Error: pm.response.success undefined }); /* Right: Parse JSON first */ pm.test('Check success', () => { const data = pm.response.json(); pm.expect(data.success).to.eql(true); });
Quick Reference
| Assertion | Purpose | Example |
|---|---|---|
| pm.response.to.have.status(code) | Check HTTP status code | pm.response.to.have.status(200) |
| pm.response.to.be.json() | Check response is JSON | pm.response.to.be.json() |
| pm.expect(value).to.eql(expected) | Compare values | pm.expect(jsonData.id).to.eql(123) |
| pm.expect(array).to.include(item) | Check array contains item | pm.expect(jsonData.tags).to.include('new') |
| pm.expect(string).to.have.length.above(n) | Check string length | pm.expect(jsonData.name).to.have.length.above(3) |
Key Takeaways
Write tests in Postman's Tests tab using pm.test() with a descriptive name and a function.
Use pm.response methods and pm.expect assertions to validate API responses.
Always parse JSON responses with pm.response.json() before accessing data.
Check for common mistakes like wrong syntax or accessing response data incorrectly.
Use the Quick Reference table to remember common assertions and their usage.