Duplicating and moving requests in Postman - Build an Automation Script
import fs from 'fs'; import { Collection } from 'postman-collection'; // Load the original collection JSON const sampleCollectionData = JSON.parse(fs.readFileSync('Sample_Collection.json', 'utf8')); const backupCollectionData = JSON.parse(fs.readFileSync('Backup_Collection.json', 'utf8')); const sampleCollection = new Collection(sampleCollectionData); const backupCollection = new Collection(backupCollectionData); // Find the request named 'Get User' const originalRequest = sampleCollection.items.one('Get User'); if (!originalRequest) { throw new Error("Original request 'Get User' not found in Sample Collection."); } // Duplicate the request const duplicatedRequest = originalRequest.clone(); duplicatedRequest.name = 'Get User Copy'; // Add duplicated request to Sample Collection sampleCollection.items.add(duplicatedRequest); // Assert duplicated request exists in Sample Collection if (!sampleCollection.items.one('Get User Copy')) { throw new Error("Duplicated request not found in Sample Collection after adding."); } // Remove duplicated request from Sample Collection sampleCollection.items.remove(duplicatedRequest); // Assert duplicated request removed from Sample Collection if (sampleCollection.items.one('Get User Copy')) { throw new Error("Duplicated request still exists in Sample Collection after removal."); } // Add duplicated request to Backup Collection backupCollection.items.add(duplicatedRequest); // Assert duplicated request exists in Backup Collection if (!backupCollection.items.one('Get User Copy')) { throw new Error("Duplicated request not found in Backup Collection after adding."); } // Save updated collections back to files fs.writeFileSync('Sample_Collection_Updated.json', JSON.stringify(sampleCollection.toJSON(), null, 2)); fs.writeFileSync('Backup_Collection_Updated.json', JSON.stringify(backupCollection.toJSON(), null, 2)); console.log('Request duplicated and moved successfully.');
This script uses the Postman Collection SDK to automate duplicating and moving a request between collections.
First, it loads the JSON files for the two collections: 'Sample Collection' and 'Backup Collection'.
It finds the original request named 'Get User' in the sample collection. If not found, it throws an error.
It clones this request and renames it to 'Get User Copy'.
The duplicated request is added to the sample collection, then verified to exist there.
Next, the duplicated request is removed from the sample collection and verified it no longer exists there.
Then, the duplicated request is added to the backup collection and verified to exist there.
Finally, the updated collections are saved back to JSON files.
This approach uses explicit checks after each step to ensure the duplication and move operations succeeded, following best practices for automation.
Now add data-driven testing to duplicate and move requests with three different request names.