- Introduction
- Fluent and expressive syntax
- Data Management
- Data Templates
- Data Store for Dynamic Values
- Built-In Schema Validation
- Flexible Assertions
- Default Configuration
- Conclusion
- Resources
Introduction
I’ve spent a fair bit of time writing API test automation. After exploring a few JavaScript-based tools and libraries, I’ve found Pactum to be particularly powerful. I wanted to take a moment to share a brief overview of my experience and why I think it stands out.
If you’re setting up a PactumJS project from scratch, I recommend starting with the official Quick Start guide, which covers installation and basic setup clearly. Additionally, this article by Marie Cruz offers a great walkthrough of writing API tests with PactumJS and Jest, especially useful for beginners.
Fluent and expressive syntax
One of the aspects I appreciate the most is how naturally you can chain descriptive methods from the spec object to build complex requests with support for headers, body payloads, query parameters, and more.
Example:
it('POST with existing username and valid password', async () => {
await spec()
.post('/auth/login') .inspect()
.withHeaders('Content-Type', 'application/json')
.withJson({
'@DATA:TEMPLATE@': 'ExistingUser'
})
.expectStatus(200) # assertion
.expectJsonSchema(authenticationSchema) # assertion
})
More on request making: https://github.com/pactumjs/pactum/wiki/API-Testing#request-making
Data Management
Data Management is a critical aspect of test automation and often one of the more challenging pain points in any automation project. Test suites frequently reuse similar request payloads, making it difficult to maintain and organize these payloads when they are scattered across different test files or folders. Without a structured approach, this can lead to duplication, inconsistency, and increased maintenance overhead. So, it is important to have an intuitive way to handle data in the test framework.
In PactumJS, data management is typically handled using data templates and data stores. These help you define reusable request bodies, dynamic data, or test user information in a clean and maintainable way.
Data Templates
Data Templates help you define reusable request bodies and user credentials. Templates can also be locally customized within individual tests without affecting the original definition.
For example, in testing different authentication scenarios:
- Valid credentials
- Invalid password
- Non-existing user
Rather than hard-coding values in each test, as it is done below:
describe('/authenticate', () => {
it('POST with existing username and valid password', async () => {
await spec()
.post('/auth/login')
.inspect()
.withHeaders('Content-Type', 'application/json')
.withJson({
username: process.env.USERNAME,
password: process.env.PASSWORD,
})
.expectStatus(200)
.expectJsonSchema(authenticationSchema)
})
it('POST with existing username and invalid password', async () => {
await spec()
.post('/auth/login')
.inspect()
.withHeaders('Content-Type', 'application/json')
.withJson({
username: process.env.USERNAME,
password: faker.internet.password(),
})
.expectStatus(401)
.expectJsonMatch('error', 'Invalid credentials')
})
it('POST with non-existing username and password', async () => {
await spec()
.post('/auth/login')
.inspect()
.withHeaders('Content-Type', 'application/json')
.withJson({
username: faker.internet.username(),
password: faker.internet.password(),
})
.expectStatus(401)
.expectJsonMatch('error', 'Invalid credentials')
})
})
define reusable templates:
// auth.js
export function registerAuthTemplates() {
stash.addDataTemplate({
ExistingUser: {
username: process.env.USERNAME,
password: process.env.PASSWORD,
},
NonExistingUser: {
username: faker.internet.username(),
password: faker.internet.password(),
}
});
}
Then load them in global setup:
// registerDataTemplates.js
import { registerAuthTemplates } from "./auth.js";
export function registerAllDataTemplates() {
registerAuthTemplates();
}
Now, tests become cleaner and easier to maintain:
it('POST with non-existing username and password', async () => {
await spec()
.post('/auth/login')
.inspect()
.withHeaders('Content-Type', 'application/json')
.withJson({
'@DATA:TEMPLATE@': 'NonExistingUser'
})
.expectStatus(401)
.expectJsonMatch('error', 'Invalid credentials')
})
Want to override part of a template?
Use @OVERRIDES@:
it('POST with existing username and invalid password', async () => {
await spec()
.post('/auth/login')
.inspect()
.withHeaders('Content-Type', 'application/json')
.withJson({
'@DATA:TEMPLATE@': 'ExistingUser',
'@OVERRIDES@': {
'password': faker.internet.password()
}
})
.expectStatus(401)
.expectJsonMatch('error', 'Invalid credentials')
})
This approach improves consistency and reduces duplication. When credential details change, updates can be made centrally in the datafactory without touching individual tests. As a result, test logic remains clean, focused on validating behaviour rather than being cluttered with data setup.
More information on data templates: https://pactumjs.github.io/guides/data-management.html#data-template
Data Store for Dynamic Values
In integration and e2e API testing, one common challenge is managing dynamic data between requests. For example, you might need to extract an authentication token from an authentication response and use it in the header of subsequent requests. Without a clean way to store and reuse this data, tests can become messy, brittle, and hard to maintain.
PactumJS provides a data store feature that allows you to save custom response data during test execution in a clean way.
Example:
Suppose you want to send a POST request to create a room, but the endpoint requires authentication. First, you make an authentication request and receive a token in the response. Using data store functionality, you can capture and store this token, then inject it into the headers of the room creation request.
describe('POST Create a New Room', () => {
beforeEach(async () => {
await spec()
.post('/auth/login')
.withHeaders('Content-Type', 'application/json')
.withJson({
'@DATA:TEMPLATE@': 'ExistingUser'
}).stores('token', 'token')
});
it('POST: Create a New Room', async () => {
await spec()
.post('/room')
.inspect()
.withHeaders('Content-Type', 'application/json')
.withHeaders('Cookie', 'token=$S{token}')
.withJson({ '@DATA:TEMPLATE@': 'RandomRoom' })
.expectStatus(200)
.expectBody({
"success": true
})
})
Data store functionality also supports json-query libraries. It enables you to extract and store specific values from complex JSON responses. This is particularly helpful when dealing with nested structures, where you only need to capture a portion of the response—such as an ID, token, or status—from a larger payload.
Example:
await spec()
.get('/room')
.inspect()
.withHeaders('Content-Type', 'application/json')
.expectStatus(200)
.stores('roomId', `rooms[roomName=${roomName}].roomid`);
await spec()
.get(`/room/$S{roomId}`)
.inspect()
.withHeaders('Content-Type', 'application/json')
.expectStatus(200)
.expectJson('roomName', roomName);
})
More on data store: https://pactumjs.github.io/guides/data-management.html#data-store
Built-In Schema Validation
Unlike other setups that require integrating libraries like zod, ajv, or custom helper functions, PactumJS allows you to validate JSON responses using the expectJsonSchema method. All you need to do is define the expected schema and apply it directly in your test, no extra configuration needed.
For example, in an authentication test case, the response schema is defined in a separate data factory:
export const authenticationSchema = {
"type": "object",
"properties": {
"token": {
"type": "string"
}
},
"additionalProperties": false,
"required": ["token"]
}
You can then validate the structure of the response like this:
it('POST with existing username and valid password', async () => {
await spec()
.post('/auth/login')
.inspect()
.withHeaders('Content-Type', 'application/json')
.withJson({
'@DATA:TEMPLATE@': 'ExistingUser'
})
.expectStatus(200)
.expectJsonSchema(authenticationSchema)
})
Flexible Assertions
Most REST API responses return data in JSON format that must be validated. Fortunately, PactumJS provides a powerful and expressive assertion system that goes far beyond basic status code checks. Its assertion system allows for
- Deep JSON matching:
await spec()
.get(`/room/$S{roomId}`)
.inspect()
.expectStatus(200)
.expectJson('roomName', roomName);
})
it('POST with non-existing username and password', async () => {
await spec()
.post('/auth/login')
.inspect()
.withJson({
'@DATA:TEMPLATE@': 'NonExistingUser'
})
.expectStatus(401)
.expectJsonMatch('error', 'Invalid credentials')
})
- Partial comparisons:
it('posts should have a item with title -"some title"', async () => {
const response = await pactum.spec()
.get('https://jsonplaceholder.typicode.com/posts')
.expectStatus(200)
.expectJsonLike([
{
"userId": /\d+/,
"title": "some title"
}
]);
});
- Path-Based Validation:
it('get people', async () => {
const response = await pactum.spec()
.get('https://some-api/people')
.expectStatus(200)
.expectJson({
people: [
{ name: 'Matt', country: 'NZ' },
{ name: 'Pete', country: 'AU' },
{ name: 'Mike', country: 'NZ' }
]
})
.expectJsonAt('people[country=NZ].name', 'Matt')
.expectJsonAt('people[*].name', ['Matt', 'Pete', 'Mike']);
});
- Dynamic Runtime Expressions:
it('get users', async () => {
await pactum.spec()
.get('/api/users')
.expectJsonLike('$V.length === 10'); // api should return an array with length 10
.expectJsonLike([
{
id: 'typeof $V === "string"',
name: 'jon',
age: '$V > 30' // age should be greater than 30
}
]);
});
And all of them are in a clean and readable format.
For example, you can validate only parts of a response, use regex or custom matchers, and even plug in JavaScript expressions or reusable assertion handlers. In my opinion, this level of granularity is a game-changer compared to assertion styles in other frameworks.
Check more in the official documentation: https://github.com/pactumjs/pactum/wiki/API-Testing#response-validation
Default Configuration
To reduce repetition and keep tests clean, PactumJS allows you to define default values that apply globally across your test suite — such as headers, base URL, and request timeouts. This helps maintain consistency and simplifies test configuration.
Here’s how it can be implemented:
before(() => {
request.setBaseUrl(process.env.BASE_URL);
request.setDefaultHeaders('Content-Type', 'application/json');
});
More information you can find here: https://github.com/pactumjs/pactum/wiki/API-Testing#request-settings
Conclusion
In my experience, PactumJS has proven to be a well-designed and developer-friendly tool for API test automation. Its fluent syntax, robust data handling, and built-in features like schema validation and dynamic stores eliminate the need for developing third-party solutions for the test framework.
If you’re working with API testing in JavaScript / Typescript, PactumJS is definitely worth a look.
Resources
- You can find the complete set of test cases, data templates, and helper functions shown in this post in the GitHub Repo.
- Official PactumJS Documentation: https://pactumjs.github.io/
- PactumJS WiKi Page: https://github.com/pactumjs/pactum/wiki/API-Testing
- Code Examples in PactumJS GitHub: https://github.com/pactumjs/pactum-examples