Verify user login API with reusable test scripts
Preconditions (3)
✅ 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.
/* 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.
Now add data-driven testing by running the login request with 3 different sets of user credentials using Postman environment variables or data files.
function followed by the function name and parentheses.function checkStatus() {
pm.test('Status is 200', () => pm.response.to.have.status(200));
}
checkStatus();checkStatus runs a test that expects the response status to be 200.function checkResponse() {
pm.test('Response time is less than 200ms', () => {
pm.expect(pm.response.responseTime).to.be.below(200);
});
}
checkResponse
What is the error and how to fix it?checkResponse is defined correctly but called without parentheses, so it does not execute.() after checkResponse calls the function properly and runs the test.to.have.property(key).that.is.not.empty which checks key existence and non-empty value.to.include.key which is invalid.to.have.key(key).not.empty.Pass the test and this pattern moves unknown