In this section, we will explore how to use scripts in Postman to enhance your API testing capabilities. Postman scripts allow you to automate tasks, manipulate data, and perform complex testing scenarios. We'll cover the basics of scripting in Postman, including pre-request and test scripts, and provide practical examples to help you get started.

Key Concepts

  1. Scripts in Postman:

    • Pre-request Scripts: These are executed before the request is sent. They are useful for setting up the environment, modifying request parameters, or generating dynamic data.
    • Test Scripts: These run after the response is received. They are used to validate the response, extract data, and perform assertions.
  2. JavaScript in Postman:

    • Postman scripts are written in JavaScript, allowing you to leverage the full power of the language to manipulate data and control the flow of your tests.
  3. Postman Sandbox:

    • A JavaScript execution environment that provides a set of libraries and functions to interact with requests and responses.

Practical Examples

Example 1: Pre-request Script

Let's create a pre-request script that generates a random user ID and adds it to the request headers.

// Generate a random user ID
const userId = Math.floor(Math.random() * 1000);

// Set the user ID in the request headers
pm.request.headers.add({ key: 'User-ID', value: userId.toString() });

console.log('User ID set to:', userId);

Explanation:

  • We use Math.random() to generate a random number and Math.floor() to convert it to an integer.
  • The pm.request.headers.add() function adds a new header to the request with the key User-ID.

Example 2: Test Script

Now, let's write a test script to validate the response status and check if a specific field exists in the response body.

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

// Validate that the response body contains a 'name' field
pm.test("Response contains 'name' field", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('name');
});

Explanation:

  • pm.test() is used to define a test case. The first argument is the test name, and the second is a function containing the test logic.
  • pm.response.to.have.status(200) checks if the response status code is 200.
  • pm.response.json() parses the response body as JSON, and pm.expect() is used to assert that the name field exists.

Exercises

Exercise 1: Dynamic Query Parameter

Task: Write a pre-request script to add a dynamic timestamp as a query parameter to the request URL.

Solution:

// Get the current timestamp
const timestamp = new Date().getTime();

// Add the timestamp as a query parameter
pm.request.url.addQueryParams({ key: 'timestamp', value: timestamp.toString() });

console.log('Timestamp added:', timestamp);

Exercise 2: Validate JSON Schema

Task: Write a test script to validate the response body against a predefined JSON schema.

Solution:

// Define the JSON schema
const schema = {
    "type": "object",
    "properties": {
        "id": { "type": "integer" },
        "name": { "type": "string" }
    },
    "required": ["id", "name"]
};

// Validate the response body against the schema
pm.test("Response matches the schema", function () {
    const jsonData = pm.response.json();
    pm.expect(tv4.validate(jsonData, schema)).to.be.true;
});

Feedback:

  • Ensure the JSON schema accurately reflects the expected structure of the response.
  • Use tv4 library functions to perform schema validation.

Conclusion

In this section, we explored how to use Postman scripts to automate and enhance your API testing. By leveraging pre-request and test scripts, you can dynamically modify requests, validate responses, and perform complex testing scenarios. Practice writing scripts to become proficient in using Postman for API testing. In the next section, we will delve into data-driven testing with Postman, allowing you to run tests with multiple data sets.

© Copyright 2024. All rights reserved