Some common test scripts in Postman

Some common test scripts in Postman

·

5 min read

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
});

Common Test Scripts

1. Status Code Validation

// Test if the response status code is 200 (OK)
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

2. Response Time Validation

// 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);
});

3. Response Body Validation

// 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");
});

4. JSON Response Validation

// Test if the response is a valid JSON
pm.test("Response is valid JSON", function () {
    pm.expect(pm.response.json()).to.be.an("object");
});

5. Header Validation

// 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");
});

6. Chaining Tests

// 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");
});

7. Dynamic Data Validation

// 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"));
});

8. Setting data from the environment variable

var jsonData = pm.response.json();
pm.environment.set("companyIdToDelete", jsonData.data._id);

9. Response Schema Validation

// 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;
});

10. Dynamic Response Validation

// 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"));
});

11. API Versioning Validation

// 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);
    });
});

12. File Upload Validation

// 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;
    });
});

13. Authentication and Authorization Testing

// 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;
    });
});

14. Data Extraction and Transformation

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));
});

15. Session Management

//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);
    });
});

16. Pagination Testing

// 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);
});

17. Load Testing

//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);
        });
    });
});

18. Database Validation

// 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.