Some common test scripts in Postman

Search for a command to run...

No comments yet. Be the first to comment.
Testing is an integral part of the software development process. When it comes to web development, testing React components is crucial to ensure that your application functions as expected. Playwright is a powerful tool that can help you automate bro...

Firebase Cloud Messaging (FCM) is a versatile cloud-based messaging platform that empowers app developers to send messages and notifications to users' devices, delivering text, images, links, and more. In this guide, we'll explore the benefits of usi...

Automated API testing with Postman is a valuable practice that helps developers and testers ensure the quality and functionality of their APIs. Postman is a user-friendly and powerful tool designed to simplify API testing and streamline the testing p...

What is GHCR? GHCR stands for Github Container registry, The GitHub Container registry allows you to host and manage your Docker container images in your personal or organization account on GitHub. One of the benefits is that permissions can be defin...
Pococare
6 posts
In this article, we will look at some usual test scripts that people often use when they write test cases.
In Postman, test scripts are written using JavaScript in the "Tests" tab after sending an API request. Each test script is associated with a specific API request and is executed automatically after the request is sent. The test script has access to the response data, request details, and various utility functions provided by Postman.
A basic test script structure looks like this:
// Test script
pm.test("Test Description", function () {
// Assertion logic goes here
});
// Test if the response status code is 200 (OK)
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// Test if the response time is less than 500ms
pm.test("Response time is within acceptable range", function () {
pm.expect(pm.response.responseTime).to.be.below(500);
});
// Test if the response body contains a specific value
pm.test("Response body contains expected data", function () {
pm.expect(pm.response.text()).to.include("expected_value");
});
// Test if the response is a valid JSON
pm.test("Response is valid JSON", function () {
pm.expect(pm.response.json()).to.be.an("object");
});
// Test if a specific header is present in the response
pm.test("Header is present in the response", function () {
pm.response.to.have.header("header_name");
});
// Chaining multiple test assertions
pm.test("Chaining multiple assertions", function () {
pm.expect(pm.response.json().property1).to.eql("value1");
pm.expect(pm.response.json().property2).to.eql("value2");
});
// Test if a specific value in the response matches the environment variable
pm.test("Dynamic data validation", function () {
pm.expect(pm.response.json().user_id).to.eql(pm.environment.get("user_id"));
});
var jsonData = pm.response.json();
pm.environment.set("companyIdToDelete", jsonData.data._id);
// Test if the response adheres to a specific JSON schema
pm.test("Response schema validation", function () {
const schema = {
"type": "object",
"properties": {
"property1": { "type": "string" },
"property2": { "type": "number" }
}
};
pm.expect(tv4.validate(pm.response.json(), schema)).to.be.true;
});
// Validate dynamic data in the response by extracting values from the response and using them in assertions.
// Extract a value from the response and use it in an assertion
pm.test("Dynamic response validation", function () {
var responseBody = pm.response.json();
var dynamicValue = responseBody.dynamic_property;
pm.expect(dynamicValue).to.equal(pm.variables.get("expected_dynamic_value"));
});
// Test different API versions
var apiVersion = "v2";
pm.test("API versioning validation", function () {
pm.request.headers.add({ key: "Accept-Version", value: apiVersion });
pm.sendRequest(function (response) {
pm.expect(response.status).to.equal(200);
pm.expect(response.json().version).to.equal(apiVersion);
});
});
// Test file upload
pm.test("File upload validation", function () {
var formData = {
file: {
value: pm.globals.get("fileData"),
options: {
filename: "sample.txt",
contentType: "text/plain"
}
}
};
pm.sendRequest({
url: "https://api.example.com/upload",
method: "POST",
body: formData
}, function (response) {
pm.expect(response.status).to.equal(200);
pm.expect(response.json().success).to.be.true;
});
});
// Test authentication and authorization
pm.test("Authentication and authorization", function () {
var authToken = pm.environment.get("authToken");
pm.request.headers.add({ key: "Authorization", value: "Bearer " + authToken });
pm.sendRequest(function (response) {
pm.expect(response.status).to.equal(200);
pm.expect(response.json().authorized).to.be.true;
});
});
Extract data from the response and transform it for further use or validation.
// Extract and transform data from the response
pm.test("Data extraction and transformation", function () {
var responseArray = pm.response.json().data;
var transformedData = responseArray.map(function (item) {
return {
id: item.id,
name: item.first_name + " " + item.last_name"
};
});
// Use transformed data for assertions or environment variables
pm.expect(transformedData[0].name).to.include("John");
pm.environment.set("transformedData", JSON.stringify(transformedData));
});
//Simulate session management by saving and reusing session tokens.
// Session management using session tokens
var sessionToken;
pm.test("Login and session management", function () {
// Perform login and extract session token from the response
sessionToken = pm.response.json().session_token;
pm.environment.set("sessionToken", sessionToken);
});
pm.test("Authenticated request using session token", function () {
// Use the saved session token for authenticated requests
pm.request.headers.add({ key: "Authorization", value: "Bearer " + sessionToken });
pm.sendRequest(function (response) {
pm.expect(response.status).to.equal(200);
});
});
// Test APIs that return paginated results and validate pagination logic.
// Pagination testing
pm.test("Pagination testing", function () {
var response = pm.response.json();
var currentPage = response.page;
var totalPages = response.total_pages;
// Validate pagination logic
pm.expect(currentPage).to.be.at.least(1);
pm.expect(currentPage).to.be.at.most(totalPages);
});
//Perform load testing by sending multiple concurrent requests.
// Load testing with concurrent requests
var concurrentRequests = 10;
pm.test("Load testing", function () {
var requests = [];
for (var i = 0; i < concurrentRequests; i++) {
requests.push(pm.sendRequest);
}
Promise.all(requests).then(function (responses) {
responses.forEach(function (response) {
pm.expect(response.status).to.equal(200);
});
});
});
// Validate API responses by comparing them with data from a database.
// Database validation using a mock database
var mockDatabase = [
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" }
];
pm.test("Database validation", function () {
var response = pm.response.json();
mockDatabase.forEach(function (item) {
var matchingItem = response.find(function (responseItem) {
return responseItem.id === item.id;
});
pm.expect(matchingItem.name).to.equal(item.name);
});
});
You can generate test cases using Postbot, which is located in the top right corner of the test case writing area.

You can write more complex test scripts using various assertions and conditions based on your API testing needs. Postman offers documentation and tutorials to help you learn more about writing test scripts and performing API testing effectively.