import newman from 'newman';
// Define environment variables
const environment = {
"id": "env1",
"name": "Local Environment",
"values": [
{ "key": "baseUrl", "value": "https://jsonplaceholder.typicode.com", "enabled": true }
]
};
// Define the Postman collection JSON
const collection = {
"info": {
"name": "API Testing Workspace",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "User API Tests",
"item": [
{
"name": "Get Users",
"request": {
"method": "GET",
"url": "{{baseUrl}}/users"
},
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 200', function () {",
" pm.response.to.have.status(200);",
"});"
]
}
}
]
}
]
},
{
"name": "Post API Tests",
"item": [
{
"name": "Create Post",
"request": {
"method": "POST",
"header": [
{ "key": "Content-Type", "value": "application/json" }
],
"body": {
"mode": "raw",
"raw": "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}"
},
"url": "{{baseUrl}}/posts"
},
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 201', function () {",
" pm.response.to.have.status(201);",
"});"
]
}
}
]
}
]
}
]
};
// Run the collection using Newman
newman.run({
collection: collection,
environment: environment,
reporters: 'cli'
}, function (err, summary) {
if (err) { throw err; }
console.log('Collection run complete!');
// Check if all tests passed
const failures = summary.run.failures.length;
if (failures === 0) {
console.log('All tests passed successfully.');
} else {
console.log(`${failures} test(s) failed.`);
}
});This script uses Newman, the command-line runner for Postman collections.
We define an environment with a base URL to keep URLs flexible.
The collection JSON defines two collections inside one workspace: 'User API Tests' and 'Post API Tests'. Each has one request with tests checking the HTTP status codes.
Newman runs the collection and outputs results in the console.
This approach follows best practices: environment variables, descriptive names, and test assertions for response codes.