MicroFrontends Classroomnotes 07/Apr/2022

Scripting for API Testing in Postman

  • Consider the following response
{
    "name": "Luke Skywalker",
    "height": "172",
    "mass": "77",
    "hair_color": "blond",
    "skin_color": "fair",
    "eye_color": "blue",
    "birth_year": "19BBY",
    "gender": "male",
    "homeworld": "https://swapi.dev/api/planets/1/",
    "films": [
        "https://swapi.dev/api/films/1/",
        "https://swapi.dev/api/films/2/",
        "https://swapi.dev/api/films/3/",
        "https://swapi.dev/api/films/6/"
    ],
    "species": [],
    "vehicles": [
        "https://swapi.dev/api/vehicles/14/",
        "https://swapi.dev/api/vehicles/30/"
    ],
    "starships": [
        "https://swapi.dev/api/starships/12/",
        "https://swapi.dev/api/starships/22/"
    ],
    "created": "2014-12-09T13:50:51.644000Z",
    "edited": "2014-12-20T21:17:56.891000Z",
    "url": "https://swapi.dev/api/people/1/"
}
  • When we try to write tests in postman, we have two styles
  • assert based expressions
  • Behavior driven Expressions
var chai = require('chai')
pm.test("Testing something", () => {
    const responseBodyInJson = pm.response.json();
    chai.assert.typeOf(responseBodyInJson.name, 'string');
    pm.expect(responseBodyInJson.name).to.be.a('string');

});
  • Testing Styles in Postman
    Preview
  • Assert Style: Refer Here for the api reference
  • Lets follow the Assert style to test the starwars people api as shown below
var chai = require('chai')
pm.test("Structure Testing", () => {
    const responseBodyInJson = pm.response.json();
    // checking if the response exists
    chai.assert.exists(responseBodyInJson, "Response should not be null or undefined");
    chai.assert.isObject(responseBodyInJson, "Response should be an object");
    chai.assert.isString(responseBodyInJson.name, "Name should be a string");
    // try to write the type is string for string fields
    chai.assert.isArray(responseBodyInJson.films, "films should be an array");

});

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner