Postman is a powerful tool for testing APIs, and one of its standout features is the ability to write custom test scripts using JavaScript. These scripts allow you to automate tests, extract data from responses, and perform complex validations. In this deep dive guide, we’ll explore the world of custom test scripts in Postman with extended code examples.
Understanding Custom Test Scripts
Custom test scripts in Postman are written in JavaScript and executed after sending a request. They are a fundamental part of your API testing workflow, enabling you to perform various actions like assertions, data extraction, and dynamic test case creation.
Here are some common tasks you can accomplish with custom test scripts:
- Validation: Check if the response status code, headers, or data match your expectations.
- Data Extraction: Extract values from the response to use in subsequent requests or tests.
- Dynamic Testing: Create dynamic test cases based on response data or conditions.
- Environment Variable Manipulation: Update environment variables based on the test results or response data.
Writing Custom Test Scripts
Custom test scripts in Postman are written in the “Tests” tab of a request. Here’s a basic structure of a custom test script:
1 2 3 |
pm.test('Test Name', function () { // Your test code goes here }); |
Let’s dive into some extended code examples to illustrate the power of custom test scripts in Postman:
1. Basic Response Validation
1 2 3 4 5 6 7 8 9 10 11 |
pm.test('Response Status Code is 200', function () { pm.response.to.have.status(200); }); pm.test('Response Time is Less Than 500ms', function () { pm.expect(pm.response.responseTime).to.be.below(500); }); pm.test('Response Body Contains "success"', function () { pm.expect(pm.response.text()).to.include('success'); }); |
In this example, we’re validating the response status code, response time, and checking if the response body contains a specific string.
2. Data Extraction
1 2 3 4 5 6 7 |
// Extract the user ID from the response JSON const jsonData = pm.response.json(); const userId = jsonData.user.id; pm.environment.set('user_id', userId); // Use the extracted user ID in the next request pm.collectionVariables.set('user_id', userId); |
Here, we’re extracting the user ID from the response JSON and storing it in environment variables for future requests.
3. Dynamic Test Cases
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Check if the response contains an array of items const jsonData = pm.response.json(); if (Array.isArray(jsonData.items)) { jsonData.items.forEach(function (item, index) { pm.test(`Item ${index + 1} has a valid ID`, function () { pm.expect(item.id).to.be.a('number'); }); }); } else { pm.test('No items found in the response', function () { pm.expect(jsonData.items).to.be.an('array'); }); } |
In this script, we’re dynamically creating test cases based on the number of items in the response. If there are items, we validate each item’s ID; otherwise, we report that no items were found.
4. Environment Variable Manipulation
1 2 3 4 5 6 7 |
// Check if the response indicates a successful login const jsonData = pm.response.json(); if (jsonData.success === true) { pm.environment.set('authenticated', 'true'); } else { pm.environment.set('authenticated', 'false'); } |
Here, we’re setting an environment variable based on whether the response indicates a successful login. This variable can be used in subsequent requests or tests to control the flow of your API testing workflow.
5. Chaining Requests
Custom test scripts can be used to automate chained requests, where the data from one request is used in subsequent requests. Here’s an example of chaining requests using custom scripts:
javascriptCopy code
// Extract a product ID from the response const productId = pm.response.json().product.id; // Set the product ID as an environment variable pm.environment.set('product_id', productId); // Trigger a second request that uses the extracted product ID pm.sendRequest({ url:
https://api.example.com/products/${productId}
, method: 'GET', }, function (response) { pm.test('Product Details Request is Successful', function () { pm.expect(response.code).to.equal(200); }); });
In this script, we extract a product ID from the response, set it as an environment variable, and then use it in a second request to retrieve detailed information about the product.
6. Advanced Response Validation
Custom test scripts in Postman allow you to perform advanced response validation. You can use libraries like Chai.js for expressive and powerful assertions. Here’s an example:
javascriptCopy code
const jsonData = pm.response.json(); // Perform deep assertions using Chai.js pm.test('Response Body Contains Required Fields', function () { pm.expect(jsonData).to.have.property('name').that.is.a('string'); pm.expect(jsonData).to.have.property('price').that.is.a('number'); pm.expect(jsonData).to.have.property('description').that.is.a('string'); }); // Validate that a specific field meets a condition pm.test('Price is Greater Than 0', function () { pm.expect(jsonData.price).to.be.greaterThan(0); }); // Perform complex assertions with logical operators pm.test('Data Integrity Check', function () { pm.expect(jsonData) .to.have.property('availability') .that.is.oneOf(['in stock', 'out of stock']) .and.not.equal('out of stock'); });
In this script, we’re using Chai.js assertions to perform deep, conditional, and complex validations on the response data.
7. Handling Edge Cases
Custom test scripts can handle edge cases and exceptional scenarios gracefully. For example, you can check for error responses and ensure that error messages are handled correctly:
javascriptCopy code
const jsonData = pm.response.json(); if (jsonData.error) { pm.test('Error Response Handling', function () { pm.expect(jsonData.error).to.have.property('code').that.is.a('number'); pm.expect(jsonData.error).to.have.property('message').that.is.a('string'); }); } else { pm.test('No Error Response', function () { pm.expect(jsonData.error).to.be.undefined; }); }
This script checks if the response contains an error object and validates its structure. If no error is present, it verifies that the error property is undefined.
8. External Libraries
Postman allows you to use external JavaScript libraries in your custom test scripts. This enables you to leverage additional functionality beyond the built-in JavaScript capabilities. For example, you can use libraries like Lodash for advanced data manipulation or Moment.js for date and time handling.
To use external libraries, you can include them in the “Pre-request Script” section of a request or in the “Tests” script if you want to use them during response validation.
javascriptCopy code
// Example of using the Lodash library const _ = require('lodash'); const jsonData = pm.response.json(); // Use Lodash to perform data manipulation const modifiedData = _.map(jsonData, (item) => { return { id: item.id, name: _.startCase(item.name), }; }); pm.test('Data Transformation Check', function () { pm.expect(modifiedData).to.be.an('array'); });
By adding external libraries to your custom scripts, you can take advantage of a wide range of functionality to streamline and enhance your API testing.
Advanced Best Practices
To take your custom test scripts to the next level, consider these advanced best practices:
- Modularity: Break down complex scripts into reusable functions for better code organization and maintainability.
- Mocking Data: Use the Postman mocking feature to simulate responses for testing various scenarios, including edge cases and error conditions.
- Performance Testing: Implement custom test scripts to measure API performance, including response times and latency.
- Continuous Integration: Integrate your Postman tests into your CI/CD pipeline to automate testing as part of your development workflow.
- Error Reporting: Set up custom error reporting to log failures and generate detailed test reports for analysis.
By mastering custom test scripts in Postman and applying these advanced techniques, you can build robust, comprehensive, and automated API test suites that ensure the reliability and functionality of your APIs across various scenarios and conditions.
Conclusion
Custom test scripts in Postman empower you to create comprehensive and automated API tests. By using JavaScript to validate responses, extract data, and perform dynamic testing, you can ensure the reliability and functionality of your APIs. Incorporate these best practices and extended code examples into your API testing workflow, and you’ll be well-equipped to handle a wide range of testing scenarios with Postman. Happy testing!