0
0
Postmantesting~15 mins

Reusable test scripts in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify user login API with reusable test scripts
Preconditions (3)
Step 1: Create a new Postman collection named 'User Authentication'
Step 2: Add a new request named 'Login' with POST method to https://api.example.com/login
Step 3: In the request body, add JSON with fields 'username' and 'password'
Step 4: Write a reusable test script in the collection's Tests tab to verify response status is 200
Step 5: Also verify the response JSON contains a 'token' field
Step 6: Save the reusable test script in the collection's Pre-request Scripts or Tests section
Step 7: Run the 'Login' request with valid credentials
Step 8: Observe that the reusable test script runs and validates the response
✅ Expected Result: The reusable test script runs after the 'Login' request and asserts the response status is 200 and the response contains a 'token' field, passing the test.
Automation Requirements - Postman
Assertions Needed:
Response status code is 200
Response JSON contains 'token' field
Best Practices:
Use collection-level test scripts for reuse
Avoid duplicating test code in individual requests
Use pm.expect assertions for clear validation
Keep test scripts simple and readable
Automated Solution
Postman
/* Collection-level Tests script in Postman */
pm.test('Response status is 200', () => {
    pm.response.to.have.status(200);
});
pm.test('Response has token field', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('token');
});

This script is placed at the collection level so it runs after every request in the collection.

First, it checks if the response status code is 200, which means success.

Second, it parses the response JSON and checks if there is a 'token' property, which indicates a successful login.

Using collection-level scripts avoids repeating the same tests in every request, making maintenance easier.

Common Mistakes - 3 Pitfalls
Writing test scripts only in individual requests instead of collection level
Not checking response status before accessing JSON fields
Using console.log instead of pm.expect for assertions
Bonus Challenge

Now add data-driven testing by running the login request with 3 different sets of user credentials using Postman environment variables or data files.

Show Hint