Skip to main content
Postman Testing
CHAPTER 13 Beginner

Writing Tests in Postman

Updated: May 13, 2026
30 min read

# CHAPTER 13

Writing Tests in Postman

1. Introduction

Up to this point, you have been doing "Manual Testing". You click Send, use your human eyes to check if the status is 200, and use your brain to verify the JSON data. If you have an API with 200 endpoints, you cannot do this manually every day. Welcome to Automated Testing. Postman includes a powerful JavaScript sandbox that allows you to write scripts that run automatically *after* a request finishes. In this chapter, we will write our first Postman Tests to validate status codes, response times, and specific JSON data.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Locate and use the "Tests" tab in the Request Builder.
  • Understand the pm.test() and pm.expect() syntax.
  • Write a basic test to verify an HTTP status code.
  • Parse a JSON response body into a JavaScript object.
  • Write assertions to validate specific data points in the JSON.
  • Use Postman's built-in "Snippets" to generate test code quickly.

3. Beginner-Friendly Explanation

Imagine a teacher grading a math test. Manual Testing: The teacher looks at the student's answer "4", remembers the correct answer is "4", and puts a checkmark on the paper. Automated Testing: The teacher uses a transparent grading stencil with holes cut out. They place the stencil over the paper. If a "4" shows through the hole, it instantly passes. If a "5" shows, it instantly fails.

In Postman, writing a test is creating that grading stencil. You write a small piece of code that says "The status code MUST be 200." When you hit Send, Postman fetches the data, applies the stencil, and instantly gives you a green PASS or a red FAIL.

4. Real-World Examples

  • Regression Testing: Before a company launches a new update, they press a single button. Postman runs 500 tests automatically. If one test fails (e.g., "Expected price to be an integer, but got a string"), the launch is stopped.
  • Performance Thresholds: You write a test that says pm.expect(pm.response.responseTime).to.be.below(500). If the API takes longer than half a second to reply, the test fails, alerting developers to a performance bottleneck.

5. The Tests Tab and Snippets

You don't have to be a JavaScript master to write Postman tests!

Step 1: Open a request (e.g., GET https://jsonplaceholder.typicode.com/users/1). Step 2: Click the Tests tab (next to Pre-request Script). Step 3: Look at the far right edge of the screen. You will see a list of blue links under the title Snippets. Step 4: Click the snippet titled "Status code: Code is 200". Postman instantly types this code for you:

javascript
123
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

6. Writing Data Validation Tests

Testing status codes is easy, but testing the actual data requires parsing the JSON.

Step 1: Parse the Response Before we can test the data, we must convert the raw text response into a JavaScript object.

javascript
12
// This line extracts the JSON body
const jsonData = pm.response.json();

Step 2: Write the Assertion Let's verify that the user's name is exactly "Leanne Graham".

javascript
1234
pm.test("Verify User's Name", function () {
    // We expect the 'name' property of our json data to equal 'Leanne Graham'
    pm.expect(jsonData.name).to.eql("Leanne Graham");
});

7. Combining Multiple Tests

You should always have multiple tests for a single endpoint. Put this entire block in your Tests tab and hit Send:
javascript
1234567891011121314151617
// Test 1: Check Status
pm.test("Status is successful", function () {
    pm.response.to.have.status(200);
});

// Test 2: Check Speed
pm.test("Response is faster than 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

// Test 3: Check Data Structure
const jsonData = pm.response.json();
pm.test("User has an email address", function () {
    pm.expect(jsonData.email).to.be.a("string");
    // You can have multiple assertions in one test!
    pm.expect(jsonData.email.length).to.be.above(0);
});

8. Viewing Test Results

After you hit Send, look at the Response Viewer (bottom half of the screen).
  1. 1. Click the Test Results tab.
  1. 2. You will see a green PASS or a red FAIL next to each test name you defined (e.g., "Verify User's Name").
  1. 3. If a test fails, Postman tells you exactly why: *AssertionError: expected 'Bob' to deeply equal 'Leanne Graham'*.

9. Best Practices

  • Use Descriptive Test Names: pm.test("Test 1") is terrible. pm.test("User object contains a valid email") is excellent. If a test fails, you want to know exactly what broke just by reading the title.
  • Fail Gracefully: If you try to parse JSON but the server returns a 500 HTML error page, pm.response.json() will crash your script. It's often safer to verify the status is 200 *before* trying to parse complex JSON.
  • Use Snippets: The snippets list on the right side of the screen contains the syntax for almost everything you need. Use them to learn!

10. Common Mistakes

  • Syntax Errors: Missing a closing parenthesis ) or bracket } in JavaScript will crash the test execution. Use the red squiggly lines in the editor to spot typos.
  • Testing Dynamic Data as Static Data: Don't write pm.expect(jsonData.timestamp).to.eql("2023-10-15") if the API returns the current date. It will pass today and fail tomorrow. Instead, test the *type*: pm.expect(jsonData.timestamp).to.be.a("string").

11. Mini Exercises

  1. 1. Look at the Snippets menu. Find the snippet that checks if a string is present anywhere in the response body. What is the code?
  1. 2. If jsonData.id equals 42, write a single line of pm.expect() code to verify it.

12. Coding/Testing Challenges

Challenge 1: Send a GET request to https://jsonplaceholder.typicode.com/posts/1. Write a script that parses the JSON and contains two tests:
  1. 1. Verify that the userId is equal to 1.
  1. 2. Verify that the title is of type "string".

13. MCQs with Answers

Question 1

What programming language is used to write Postman Tests?

Question 2

What object gives you access to the data returned by the server inside a Postman test script?

Question 3

If you want to check if the server responded in less than 200 milliseconds, which property do you evaluate?

14. Interview Questions

  • Q: Explain the process of validating a JSON response in Postman from start to finish.
  • Q: What is an "Assertion" in the context of API testing? Give an example of syntax used in Postman (Chai library).
  • Q: Why is automated testing via Postman scripts preferred over manual verification?

15. FAQs

Q: Does my test code run before or after the API request is sent? A: Code in the Tests tab runs *after* the response is received. If you want to run code *before* the request is sent (like generating a random timestamp to include in the body), you put it in the Pre-request Script tab.

16. Summary

In this chapter, we made the massive leap from manual testers to automation engineers. We discovered the "Tests" tab and learned how to use the pm.test() function. We learned how to extract the JSON response using pm.response.json() and wrote assertions using pm.expect() to programmatically verify status codes, response times, and specific data points. We also leaned on Postman's built-in Snippets to generate JavaScript code quickly.

17. Next Chapter Recommendation

You can now automate a single request. But what if you have a Collection of 50 requests? Do you sit there and click "Send" 50 times? No! Proceed to Chapter 14: Automating API Testing to learn how to run entire test suites at the push of a button.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·