CodeWithMMAK
API AutomationIntermediate

A Complete Guide to PactumJS: Modern REST API Testing

Master PactumJS, the next-generation REST API testing tool for JavaScript. Learn how to automate E2E, integration, contract, and component tests with ease.

CodeWithMMAK
January 20, 2023
10 min

Introduction

🎯 Quick Answer

PactumJS is a powerful, open-source REST API testing tool for Node.js. It is designed to simplify E2E, Integration, Contract, and Component testing. To get started, install it via npm install pactum, and use its fluent API to chain requests and assertions, such as await spec().get(url).expectStatus(200).

In the evolving landscape of microservices, API testing has become more critical than ever. PactumJS stands out by offering a unified interface for various testing levels, inspired by popular tools like Frisby and Pact, but with a modern, asynchronous approach.

📖 Key Definitions

PactumJS

A REST API testing library for Node.js that focuses on simplicity and readability.

Contract Testing

A technique for testing an integration point by checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding.

Component Testing

Testing a single service or component in isolation, often using mocks for external dependencies.

Fluent API

An object-oriented API whose design relies extensively on method chaining to improve code legibility.

Why Choose PactumJS?

  • Unified Tooling: One library for E2E, Integration, and Contract tests.
  • Built-in Mock Server: Easily mock external dependencies without extra tools.
  • Data Management: Powerful features for handling dynamic data and state across tests.
  • Readable Syntax: Chained methods make tests look like documentation.

🚀 Step-by-Step Implementation

1

Prerequisites

Ensure you have Node.js (v12+) installed on your machine.

2

Initialize Your Project

Create a new directory and run:

Code Snippet
mkdir pactum-tests && cd pactum-tests
npm init -y
3

Install Dependencies

Install Pactum and a test runner like Mocha:

Code Snippet
npm install --save-dev pactum mocha @faker-js/faker
4

Write Your First Test

Create a file named api.test.js:

Code Snippet
const { spec } = require('pactum');

describe('User API Tests', () => {
  it('should fetch user details', async () => {
    await spec()
      .get('https://reqres.in/api/users/2')
      .expectStatus(200)
      .expectJsonLike({
        data: { id: 2 }
      });
  });
});
5

Run the Tests

Execute your tests using Mocha:

Code Snippet
npx mocha api.test.js

Advanced E2E Testing Strategy

A robust API testing suite should cover the entire lifecycle of a resource:

  1. POST: Create a resource with dynamic data (use @faker-js/faker).
  2. Capture Data: Store the ID from the response using .stores('userId', 'data.id').
  3. GET: Fetch the resource using the captured ID: .get('users/{id}').withPathParams('id', '$S{userId}').
  4. PUT/PATCH: Update the resource and verify the changes.
  5. DELETE: Remove the resource and verify a 204 or 404 status on subsequent requests.

Common Errors & Best Practices

⚠️ Common Errors & Pitfalls

  • Unhandled Promise Rejection

    PactumJS is asynchronous. Forgetting the await keyword before spec() will cause tests to finish before the API call completes.

  • Incorrect JSON Path

    When using .expectJson(), ensure your path matches the response structure exactly. Use .expectJsonLike() for partial matches.

  • Mock Server Conflicts

    If running multiple tests in parallel, ensure your mock server ports don't overlap.

Best Practices

  • Use Data Templates for reusable request bodies to keep your tests clean and maintainable.
  • Leverage the Built-in Mock Server to simulate slow responses or error codes from third-party APIs.
  • Implement Retry Logic for flaky environments using .retry() to improve test stability.
  • Organize tests into Suites and use before hooks to set up global configurations like base URLs.

Frequently Asked Questions

Can I use PactumJS with Jest?

Yes, PactumJS works perfectly with Jest, Mocha, Cucumber, or any other JavaScript test runner.

Does it support GraphQL?

Yes, PactumJS has built-in support for sending GraphQL queries and mutations.

How do I handle Authentication?

You can use .withHeaders('Authorization', 'Bearer token') or create a custom handler to inject tokens into every request.

Conclusion

PactumJS is a versatile and developer-friendly library that simplifies the complexities of API testing. Its ability to handle everything from simple GET requests to complex contract tests within a single framework makes it an excellent choice for modern JavaScript-based QA teams.

📝 Summary & Key Takeaways

PactumJS is a comprehensive REST API testing tool for Node.js that supports E2E, integration, contract, and component testing. Its fluent API and asynchronous nature make it highly readable and performant. Key features include a built-in mock server, powerful data management, and seamless integration with popular test runners like Mocha and Jest. By following a structured testing strategy—from resource creation to deletion—and adhering to best practices like using data templates and mock servers, teams can build highly reliable and maintainable API automation suites.

Share it with your network and help others learn too!

Follow me on social media for more developer tips, tricks, and tutorials. Let's connect and build something great together!