Introduction
As discussed in the previous article, PactumJS is an excellent choice for API automation testing.
As your API testing suite grows, maintaining a clean and organized repository structure becomes essential. We’ll explore a folder structure for your PactumJS-based testing framework, provide tips and tricks for configuration and scripting, and walk through executing tests with reporting.
For demonstration, we’ll use the Restful Booker API as our test target.
Set Up Your Project and Install Dependencies
Prerequisites
To follow along, make sure you have the following:
- Node.js v10 or above
- Basic understanding of JavaScript or TypeScript
- Node.js modules
- Testing frameworks like Mocha
If you’re new to any of the above, it’s worth reviewing basic tutorials, for example, on Automation University: on Node.js and test runners like Mocha.
Install Dependencies
Start by creating a fresh Node.js project:
mkdir api_testing_with_pactumjs
cd api_testing_with_pactumjs
npm init -y
Then install necessary packages via NPM:
# install pactum
npm install -D pactum
# install a test runner
npm install -D mocha
Organise your files
api_testing_with_pactumjs/
├── helpers/
│ └── datafactory/
├── tests/
│ └── auth.spec.ts
├── setup/
│ └── base.js
├── .env.example
├── .gitignore
├── README.md
├── package-lock.json
└── package.json
- tests/ folder contains your test specifications organized by feature or endpoint, such as auth.spec.ts. This keeps tests modular and easy to locate.
- helpers/ folder houses centralized reusable logic and utilities. This separation keeps test files focused on what they test rather than how, improving readability and maintainability.
- setup/ folder contains global setup files like base.js to configure common test environment settings, such as base URLs and global hooks.
- .env.example — A sample environment configuration file listing required environment variables, serving as a reference and template for developers.
- .env (not shown in repo) is used locally to store sensitive configuration and secrets, enabling easy environment switching without code changes.
- .gitignore file includes folders and files like .env to prevent committing sensitive data to version control.
- package.json is a central place for managing project dependencies (like pactum, dotenv, mocha) and defining test scripts (e.g., npm run test, npm run test:report). This facilitates CI/CD integration and consistent test execution.
Write a Basic Test
As an example for our demo we will take the Restful-Booker Platform built by Mark Winteringham. This application has been created for bed-and-breakfast (B&B) owners to manage their bookings.
To explore and test the available API endpoints, you can use the official Postman Collection.
Let’s write our first set of API tests for the /auth/login endpoint which generates a token for an admin user.
Endpoint: POST /api/auth/login
Base URL: https://automationintesting.online
User Context
User Role: Admin (default user)
Credentials Used:
- username: “admin”
- password: “password”
Request:
Method: POST
Headers: Content-Type: application/json
Body:
{
"username": "admin",
"password": "password"
}
Expected Response:
HTTP Status: 200 OK
/ tests/authenticate.spec.js
import pkg from 'pactum';
const { spec, stash } = pkg;
describe('/authenticate', () => {
it('should succeed with valid credentials', async () => {
await spec()
.post('https://automationintesting.online/api/auth/login')
.withJson({
username: 'admin',
password: 'password'
})
.expectStatus(200)
});
});
While this test currently focuses on verifying the status code, future articles will enhance it by adding validations for the authentication token returned in the response.
Manage Environment Variables
Create .env file
To keep sensitive data like URLs and credentials, create a .env.example file as a reference for required environment variables:
BASE_URL=""
USERNAME=""
PASSWORD=""
👉 Tip: Don’t commit your actual .env to version control
- Use .env.example to document the required variables.
- Add .env to your .gitignore file to keep credentials secure.
- Share .env.example with your team so they can configure their environments consistently.
Load Environment Variables in Tests
Install dotenv and configure it in your test files or setup scripts:
npm install --save-dev dotenv
Example test with environment variables:
// tests/authenticate.spec.js
import pkg from 'pactum';
const { spec } = pkg;
import dotenv from 'dotenv';
dotenv.config();
describe('/authenticate', () => {
it('should succeed with valid credentials', async () => {
await spec()
.post(`${process.env.BASE_URL}/auth/login`)
.withJson({
username: process.env.USERNAME,
password: process.env.PASSWORD
})
.expectStatus(200);
});
});
Execute Test Case
Once your test files are set up and your .env file is configured with valid credentials and base URL, you’re ready to execute your test cases.
PactumJS works seamlessly with test runners like Mocha, which means running your tests is as simple as triggering a test command defined in your package.json. Here’s how to proceed:
Add a Test Script
In your package.json, add a script under “scripts” to define how to run your tests. For example:
// package.json
"scripts": {
"test": "mocha tests"
}
This tells Mocha to look for test files in the tests/ directory and run them.
Run the Tests
In your terminal, from the root of your project, run:
npm test
This will execute test specs and display results in the terminal.
You should see output indicating whether the test passed or failed, for example:
/authenticate
✓ should succeed with valid credentials (150ms)
1 passing (151ms)
Add a Reporting Tool
By default, PactumJS uses Mocha’s basic CLI output. For richer reporting—especially useful in CI/CD pipelines—you can use Mochawesome, a popular HTML and JSON reporter for Mocha.
Install Mochawesome
Install Mochawesome as a development dependency:
npm install -D mochawesome
Update Your Test Script
Modify the scripts section in your package.json to include a command for generating reports:
// package.json
"scripts": {
"test": "mocha tests"
"test:report": "mocha tests --reporter mochawesome"
}
This script tells Mocha to run your tests using the Mochawesome reporter.
Run the tests with reporting
Execute your tests using the new script:
npm run test:report
This generates a mocha report in JSON and HTML format which you can review locally or attach in CI pipelines.
/authenticate
✔ should succeed with valid credentials (364ms)
1 passing (366ms)
[mochawesome] Report JSON saved to ./pactum_test/mochawesome-report/mochawesome.json [mochawesome] Report HTML saved to ./pactum_test/mochawesome-report/mochawesome.html
View the report
Open the HTML report in your browser to visually inspect test results:
Configure Base Test Setup (base.js)
Create a Shared Configuration
Create a base.js file in the setup/ directory. This file is a shared configuration used to define reusable logic like setting the base URL, request headers, or global hooks (beforeEach, afterEach).
// setup/base.js
import pactum from 'pactum';
import dotenv from 'dotenv';
dotenv.config();
const { request } = pactum;
before(() => {
request.setBaseUrl(process.env.BASE_URL);
});
Load the Setup Automatically Using –file
To ensure this configuration runs before any tests, register the setup file using Mocha’s –file option. This guarantees Mocha will execute base.js within its context, making all Mocha globals (like before) available.
Example package.json script:
"scripts": {
"test": "mocha tests --file setup/base.js"
}
With this in place, run:
npm test
👉 Tip: Simplify and DRY Up Your Test Scripts
To avoid repeating the full Mocha command in multiple scripts, define a single base script (e.g., test) that includes your common options. Then, reuse it for other variants by passing additional flags:
"scripts": {
"test": "mocha tests --file setup/base.js",
"test:report": "npm run test -- --reporter mochawesome"
}
This approach keeps your scripts concise and easier to maintain by centralizing the core test command. It also allows you to easily extend or customize test runs with additional options without duplicating configuration. Overall, it reduces the chance of errors and inconsistencies when updating your test scripts.
Conclusion
By structuring your PactumJS repository with clear separation of tests, helpers, and setup files—and by leveraging environment variables, global setup, and reporting—you build a scalable and maintainable API testing framework. This approach supports growth, team collaboration, and integration with CI/CD pipelines.













