PactumJS in Practice: Using Data Templates to Manage Test Data – Part 2

Utilize faker Library to Compile Dynamic Test Data

Introduction

In Part 1, we explored how to make API tests more maintainable by introducing data templates for the /auth/login endpoint. We saw how to use @DATA:TEMPLATE, @OVERRIDES, and @REMOVES can simplify test logic and reduce duplication.

Now, in Part 2, we’ll apply the same approach to another key endpoint: POST /room – Create a new room

This endpoint typically requires structured input like room names, types, and status — perfect candidates for reusable templates. We’ll define a set of room templates using Faker for dynamic test data, register them alongside our auth templates, and write test cases that validate room creation.

Let’s dive into how data templates can help us test POST /room more effectively, with minimal boilerplate and maximum clarity.

Exploring the API Endpoint

Step 1: Inspecting the API with DevTools

Before automating, it’s helpful to understand the structure of the request and response. Visit https://automationintesting.online and follow the steps shown in the GIF below, or use the guide here:

  1. Open DevTools: Press F12 or right-click anywhere on the page and select Inspect to open DevTools.
  2. Navigate to the Network Tab. Go to the Network tab to monitor API requests.
  3. Trigger the API Call: On the website, fill in the room creation form and submit it. Watch for a request to the /room endpoint using the POST method.

Inspect the API Details. 

Once you click the POST rooms request, you will see the following details:

  1. URL and method details.
  1. Headers tab: Shows request URL and method
  2. Payload tab: Shows the room data you sent (like number, type, price, etc.)
  1. Response tab: Shows the response from the server (confirmation or error)

Example payload from this API request:

{
  "roomName":"111",
  "type":"Single",
  "accessible":false,
  "description":"Please enter a description for this room",
  "image":"https://www.mwtestconsultancy.co.uk/img/room1.jpg",
  "roomPrice":"200",
  "features":[
      "WiFi",
      "TV",
      "Radio"
  ]
}

Field Breakdown:

  • roomName: A string representing an identifier for the room (e.g., “111”).
  • type: Room type; must be one of the following values: “Single”, “Double”, “Twin”, “Family”, “Suite”.
  • accessible: A boolean (true or false) indicating whether the room is wheelchair accessible.
  • description: A text description of the room.
  • image: A URL to an image representing the room.
  • roomPrice: A string representing the price of the room.
  • features: An array of one or more of the following feature options: “WiFi“, “Refreshments“, “TV“, “Safe“, “Radio“, “Views“.

⚠️ Note: This breakdown is based on personal interpretation of the API structure and response; it is not taken from an official specification.

In order to generate payload for the room, we will use faker library. This library allows you to generate realistic test data such as names, prices, booleans, or even images on the fly. This helps reduce reliance on hardcoded values and ensures that each test run simulates real-world API usage.

Step 2: Installing the faker Library

To add the faker library to your project, run:

npm install @faker-js/faker

Step 3: Registering a Dynamic Room Template

Use faker to generate dynamic values for each room field:

// helpers/datafactory/templates/randomRoom.js

import { faker } from '@faker-js/faker/locale/en';
import pkg from 'pactum';
const { stash } = pkg;

const roomType = ["Single", "Double", "Twin", "Family", "Suite"];
const features = ['WiFi', 'Refreshment', 'TV', 'Safe', 'Radio', 'Views'];

export function registerRoomTemplates() {
  stash.addDataTemplate({
    RandomRoom: {
      roomName: faker.word.adjective() + '-' + faker.number.int({ min: 100, max: 999 }),
      type: faker.helpers.arrayElement(roomType),
      description: faker.lorem.sentence(),
      accessible: faker.datatype.boolean(),
      image: faker.image.urlPicsumPhotos(),
      features: faker.helpers.arrayElements(features, { min: 1, max: 6 }),
      roomPrice: faker.commerce.price({ min: 100, max: 500, dec: 0 })
    }
  });
}

Step 4: Writing the Test Case

Register the template:

//helpers/datafactory/templates/registerDataTemplates.js

import { registerAuthTemplates } from "./auth.js";

export function registerAllDataTemplates() {
    registerAuthTemplates();
    registerRoomTemplates();
  }

With the template registered, you can now use it in your test:

import pactum from 'pactum';
const { spec, stash } = pactum;

it('POST: Create a New Room', async () => {
    await spec()
        .post('/room')
        .withJson({ '@DATA:TEMPLATE@': 'RandomRoom' })
        .expectStatus(200)
        .expectJson({
            "success": true
        })
})

This approach ensures that each test scenario works with fresh, random input — increasing coverage and reliability.

Step 5: Running the Test

Run your tests using:

npm run test

Most likely you got 401 Unauthorized response, which means authentication is required.

Don’t worry — we’ll handle authentication, by passing the token from the login endpoint to other calls, in the next article.

Comments

Leave a comment