Writing Tests in Postman
# 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()andpm.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:
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.
Step 2: Write the Assertion Let's verify that the user's name is exactly "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:8. Viewing Test Results
After you hit Send, look at the Response Viewer (bottom half of the screen).- 1. Click the Test Results tab.
-
2.
You will see a green
PASSor a redFAILnext to each test name you defined (e.g., "Verify User's Name").
- 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. Look at the Snippets menu. Find the snippet that checks if a string is present anywhere in the response body. What is the code?
-
2.
If
jsonData.idequals42, write a single line ofpm.expect()code to verify it.
12. Coding/Testing Challenges
Challenge 1: Send a GET request tohttps://jsonplaceholder.typicode.com/posts/1. Write a script that parses the JSON and contains two tests:
-
1.
Verify that the
userIdis equal to1.
-
2.
Verify that the
titleis of type "string".
13. MCQs with Answers
What programming language is used to write Postman Tests?
What object gives you access to the data returned by the server inside a Postman test script?
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 thepm.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.