0
0
PostmanHow-ToBeginner ยท 4 min read

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 code
  • pm.response.to.be.json() - checks if response is JSON
  • pm.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 Tests tab 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

AssertionPurposeExample
pm.response.to.have.status(code)Check HTTP status codepm.response.to.have.status(200)
pm.response.to.be.json()Check response is JSONpm.response.to.be.json()
pm.expect(value).to.eql(expected)Compare valuespm.expect(jsonData.id).to.eql(123)
pm.expect(array).to.include(item)Check array contains itempm.expect(jsonData.tags).to.include('new')
pm.expect(string).to.have.length.above(n)Check string lengthpm.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.