</>

Technology

Postman

Difficulty

Beginner

Interview Question

How do you use test scripts in Postman?

Answer

Test Scripts in Postman

Test scripts run after a response is received. They are written in JavaScript and use Postman''s pm API to validate API responses.

Location

Tests tab → bottom panel of any request

Common Test Assertions

Status Code Checks

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

// Check status code is in range 2xx
pm.test("Success status", function () {
    pm.expect(pm.response.code).to.be.oneOf([200, 201, 204]);
});

Response Body Assertions

JavaScript
// Parse JSON body
const jsonData = pm.response.json();

pm.test("User name is correct", function () {
    pm.expect(jsonData.data.first_name).to.eql("Janet");
});

pm.test("ID exists", function () {
    pm.expect(jsonData.data.id).to.be.a("number");
});

pm.test("Email format", function () {
    pm.expect(jsonData.data.email).to.include("@");
});

Response Time Check

JavaScript
pm.test("Response time is under 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

Header Validation

JavaScript
pm.test("Content-Type is JSON", function () {
    pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});

Save Values for Chaining

JavaScript
pm.test("Save user ID", function () {
    const jsonData = pm.response.json();
    pm.environment.set("user_id", jsonData.data.id);
});

Quick Snippets

Postman provides code snippets in the right panel of the Tests tab:

  • "Status code: Code is 200"
  • "Response body: JSON value check"
  • "Response time is less than 200ms"
  • "Response headers: Content-Type header check"

Click any snippet to insert it automatically!

Follow AutomateQA

Related Topics