Test Scripts
Writing Tests in Postman: The “Scripts” Tab
In Postman, tests used to be written under a tab called “Tests,” but now that’s been merged into the “Scripts”
tab. After you get a response from your API,
you can write tests in the “post-response” section of the “Scripts” tab.
Best Practices for Writing Tests
If you follow some simple guidelines when writing your tests, they’ll be clearer, easier to maintain, and more
reliable. Let’s go through some tips:
1. Give Your Tests Clear Names
Why?
When your test names clearly explain what they’re checking, it’s much easier for you (and anyone else) to
understand them quickly.
Example: Instead of calling a test "Test 1" or "Status Check," you could call it “Check if Status Code is 200 for
User Endpoint” or “Ensure Response Time is Under 500ms.”
2. Test One Thing at a Time
When you test only one thing in each test, it’s easier to figure out what went wrong if a test fails. You’ll know
exactly what to fix.
Example: If you're checking both the status code and the response time, do them in separate tests:
// Test for status code
// Test for response time
3. Be Direct with Your Language
Using clear, direct language in your tests makes them easier to read. You want to be very clear about what your
test is checking.
Example: Instead of saying something unclear, use phrases like:
- expect(response).to. Contain…
- response. should. have…
These make it clear what you expect from the API response.
4. Organize Tests by Type
Why?
Organizing tests makes it easier to find and understand them. If your tests are grouped well, it’s simpler to
know what each one is checking.
Example: If you’re testing a user API, you could organize your tests into groups like:
- User creation
- User data retrieval
- User deletion
5. Test Different Scenarios, Not Just the Happy Path
Why?
It’s important to test for edge cases and errors, not just the “perfect” scenario where everything works. That
way, you’ll catch bugs that happen in less common situations.
Example: Along with testing a successful API call, write tests for errors, like:
- Invalid inputs
- Unauthorized access
- Server errors
// Test for invalid input
6. Make Your Tests Easy to Maintain and Reuse
Why?
Writing reusable tests saves time. If you find yourself repeating the same code in multiple tests, it’s better to
write a reusable function that you can use in different tests.
7. Add Comments and Documentation
Why?
Writing comments in your tests helps you (and others) understand why you wrote the test a certain way. This is
especially helpful for more complicated tests.
Example: If you have complex logic or are testing something tricky, add a quick note to explain it so anyone
reading your tests can follow along easily.
What is Chai?
Chai is a tool used in JavaScript to make sure that the code or responses from an API are correct. It's like a
helper that checks if everything is working as expected.
When you're testing something, like an API, Chai helps you confirm that things are right or wrong.
Why Do We Need Assertion Libraries Like Chai?
Imagine you’re baking a cake, and you need to make sure every ingredient is in the right amount. Chai does
something similar for code or API responses.
It checks if things are working the way they should. Here’s how it helps:
Verification: Chai checks if the output (or result) matches what you expect.
Readability: It’s written in a way that’s easy for anyone to understand, even if they’re not a developer.
Robust Testing: Chai has a lot of different checks, so you can test many aspects of an API, like data and
performance.
Using "expect" in Postman:
In Postman, “expect” helps you check if the response you get from the API is correct. Let’s look at a simple
example:
pm. test: This is like creating a little test that says, “I’m going to check something.”
pm. expect (): This is where you ask Postman to check if the response (the result you get from the API) is what
you want.
. [Link]("object"): You’re saying you expect the response to be an "object" (like a collection of key-value pairs).
What Should You Check in API Responses?
When you test APIs, there are a few key things you should always check:
Status Code: This is like a signal from the API telling you if the request was successful or if there was a problem
(like a 404 error for a page not found).
Response Body: This is the actual data the API sends back. You need to make sure it’s in the right structure and
contains the correct information.
Response Headers: These are like extra details about the response, such as the type of data (e.g., JSON) or rules
on how to cache it.
Response Time: This checks how fast the API responds. You want it to be quick!
When you're testing an API in Postman, `pm. response` is a helpful tool that lets you get information about the
response you get after sending a request. This helps you check if everything is working as expected. Here’s how
you can use it:
1. Status Code:
This tells you if the request was successful or not. For example, if the API is working fine, it usually returns a
200-status code (which means “OK”).
2. Response Time:
This shows you how long the API took to respond. It’s useful to see if the response is fast enough.
3. Headers:
Headers contain extra info about the response, like what type of data you're getting (e.g., JSON, XML). You can
check if the "Content-Type" is JSON.
4. Body:
The response body is where the actual data returned by the API is stored. You can use `pm. response. json()` to
turn it into a readable format (JSON, in this case) and check if the data matches your expectations.
In short:
- Status Code: Was the request successful?
- Response Time: How fast was the API?
- Headers: What type of data did we get back?
- Body: Does the data match what we expect?
By using `pm. response` in Postman, you can test if everything in the API works as it should. It helps you confirm
that your API is responding correctly with the right data, speed, and headers.
Using `pm. response` for Complex Checks
1. Checking Response Structure:
Sometimes, you want to make sure that the response from the server is in the right format. For example, if you
expect the response to have certain fields or a certain structure, you can use `pm. response` to check for that.
2. Conditional Tests:
This means running different tests based on the response status. For example:
- If the response is successful (status code 200) **, you might check if the data looks good.
- If the response is an error (status code 400) **, you might check if the error message is as expected.
3. Validating Dynamic Data:
Some data in the response changes every time, like timestamps or unique IDs. Instead of checking the exact
value, you can use `pm. response` to check if the format of these changing values is correct (for example, if the
timestamp looks like a valid date).
Best Practices with `pm. response`
1. Make Your Tests Easy to Read:
Try to keep your tests simple. If you make them too complex, it can be hard to understand what’s being tested,
and it can become harder to maintain later.
2. Handle Errors Well:
Always check if the response body is there before you try to use it. This way, you won’t run into issues if the
response doesn’t have what you expect.
3. Be Consistent:
Try to use `pm. response` in the same way across all your tests. This consistency will make your test scripts
easier to maintain and scale as your project grows.
1. Validating Response Status Code
- Single Status Code:
Imagine you’re testing an API, and you expect it to return a "200 OK" status. You can write a simple test to
check if the response status is what you expect.
- Multiple Status Codes:
Sometimes, an API might return different success codes like 200 or 201. You can check if the status code is
either one of them:
2. Validating Response Time
You might want the response to be quick, for example, under 500ms. Here’s how you can check the response
time:
3. Validating Response Headers
Sometimes, you want to make sure the response headers are correct, like ensuring the content type is
`application/Json`. You can do that like this:
4. Validating Response Body
- Check specific fields in the response:
Suppose you’re testing an API where you expect to get information about a character, like the `id` and `name`.
Here's how you check if they are correct:
- Check if the response matches a schema:
You might want to validate that the response matches a specific structure (or schema). Here's an example of
testing a character's details:
- Test Nested Fields:
Sometimes, data is nested in the response, like `[Link]`. You can check if those nested fields exist:
- Check Array Values:
If the response contains an array (like `episode`), and you want to validate the values at specific positions, you
can do something like this:
In Short:
- You can test different parts of the response like the status code, response time, headers, specific fields,
schemas, and even nested or array values.
- These tests ensure that the API is returning what you expect, and they help you catch any errors early.
Follow for testing content updates:
[Link]