Skip to content

Demo API Contract Testing with Pact-JS and TypeScript - Comprehensive contract testing setup demonstrating consumer-driven contract testing principles

Notifications You must be signed in to change notification settings

debasisj/pact-contract-testing

Repository files navigation

Employee API Contract Testing with Pact-JS

This project demonstrates contract testing for the Employee Management API using Pact-JS and TypeScript.

Overview

Contract testing ensures that the communication between different services remains consistent and reliable. This project implements both consumer and provider contract tests for the Employee Management API.

Project Structure

├── api-spec/
│   └── emp.yaml                 # OpenAPI specification
├── src/
│   ├── types/
│   │   └── employee.types.ts    # TypeScript interfaces
│   ├── consumer/
│   │   └── employee-client.ts   # API client implementation
│   └── provider/
│       └── mock-employee-provider.ts  # Mock provider for testing
├── tests/
│   ├── consumer/
│   │   └── employee-consumer.test.ts  # Consumer contract tests
│   └── provider/
│       └── employee-provider.test.ts  # Provider contract tests
├── pacts/                       # Generated Pact files
└── logs/                        # Pact logs

Features

  • Complete API Coverage: Tests all CRUD operations for employees
  • HATEOAS Support: Validates hypermedia links in responses
  • Error Handling: Tests various error scenarios (404, 400, etc.)
  • Type Safety: Full TypeScript support with strict typing
  • Realistic Data: Uses proper employee roles and validation rules

API Endpoints Tested

  • GET /employees - Get all employees with pagination and HATEOAS links
  • GET /employees/{id} - Get employee by ID with HATEOAS links
  • POST /employees - Create new employee with validation
  • PUT /employees/{id} - Update existing employee
  • DELETE /employees/{id} - Delete employee

Employee Roles

The API supports the following employee roles:

  • Developer
  • Manager
  • Designer
  • QA Engineer
  • DevOps
  • Product Manager

Setup and Installation

  1. Install dependencies:

    npm install
  2. Build the project:

    npm run build

Running Tests

Consumer Tests

Consumer tests verify that the client can interact with the provider according to the contract:

npm run test:consumer

Provider Tests

Provider tests verify that the provider implementation satisfies the contract:

npm run test:provider

All Tests

Run both consumer and provider tests:

npm test

Pact Workflow

  1. Consumer Tests Generate Pact: Consumer tests create a Pact file describing expected interactions
  2. Provider Tests Verify Pact: Provider tests validate that the implementation satisfies the contract
  3. Pact Files: Generated contracts are stored in the ./pacts directory

Contract Examples

Get All Employees Contract

{
  "description": "a request for all employees",
  "request": {
    "method": "GET",
    "path": "/employees"
  },
  "response": {
    "status": 200,
    "body": {
      "_embedded": {
        "employeeList": [
          {
            "id": 1,
            "name": "John Doe",
            "role": "Developer",
            "_links": {
              "self": { "href": "http://localhost:8080/employees/1" },
              "employees": { "href": "http://localhost:8080/employees" }
            }
          }
        ]
      },
      "_links": {
        "self": { "href": "http://localhost:8080/employees" }
      }
    }
  }
}

Create Employee Contract

{
  "description": "a request to create a new employee",
  "request": {
    "method": "POST",
    "path": "/employees",
    "body": {
      "name": "Jane Smith",
      "role": "Manager"
    }
  },
  "response": {
    "status": 200,
    "body": {
      "id": 1,
      "name": "Jane Smith",
      "role": "Manager"
    }
  }
}

Error Scenarios Tested

  • 404 Not Found: Employee doesn't exist
  • 400 Bad Request: Invalid data (empty fields, invalid roles, duplicate names)
  • Validation Errors: Comprehensive validation error messages

State Management

Provider tests use state handlers to set up test conditions:

  • employees exist: Sets up test data with multiple employees
  • no employees exist: Ensures empty employee list
  • employee with id X exists: Sets up specific employee
  • employee does not exist: Ensures no test data

Best Practices Implemented

  1. Consumer-Driven Contracts: Consumers define what they need
  2. Provider States: Clear test state management
  3. Realistic Test Data: Uses actual business domain data
  4. Comprehensive Coverage: Tests happy paths and error scenarios
  5. Type Safety: Strong TypeScript typing throughout
  6. HATEOAS Testing: Validates hypermedia API patterns

Integration with CI/CD

The setup supports integration with Pact Broker for sharing contracts across teams:

# Publish contracts to Pact Broker
npm run pact:publish

# Check if safe to deploy
npm run pact:can-i-deploy

Environment Variables

For Pact Broker integration:

  • PACT_BROKER_BASE_URL: Pact Broker URL
  • PACT_BROKER_USERNAME: Authentication username
  • PACT_BROKER_PASSWORD: Authentication password

Troubleshooting

Common Issues

  1. Port Conflicts: Ensure ports 8080 and 9999 are available
  2. Missing Dependencies: Run npm install to install all dependencies
  3. TypeScript Errors: Run npm run build to check for compilation issues

Logs

Pact logs are available in the ./logs directory for debugging test failures.

Contributing

  1. Add new test scenarios in the appropriate test files
  2. Update types if API changes
  3. Ensure both consumer and provider tests pass
  4. Update documentation for new features

About

Demo API Contract Testing with Pact-JS and TypeScript - Comprehensive contract testing setup demonstrating consumer-driven contract testing principles

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published