Payment Gateway Integration

How to Build Automated Payment Gateway Integration Tests

Introduction Payment gateways are essential for e-commerce websites, SaaS platforms, online marketplaces, and subscription-based applications. However,…

D
DevByteTechnical Author
Published
29 min read4 views
How to Build Automated Payment Gateway Integration Tests

Online payments are one of the most important parts of modern applications. Whether you are building an e-commerce website, a subscription platform, a booking system, or a digital marketplace, your application needs a reliable way to process payments.

But integrating a payment gateway is not just about connecting an API and accepting payments.

You also need to make sure that successful payments are recorded correctly, failed transactions are handled properly, duplicate requests do not create duplicate charges, and refunds update the application's records accurately.

This is where automated payment gateway integration testing becomes essential.

Automated integration tests help verify that your application communicates correctly with a payment provider and handles different transaction outcomes as expected. They can catch problems before they affect real customers or cause financial discrepancies.

In this guide, you will learn:

  • What automated payment gateway integration testing is.

  • Why payment integration testing matters.

  • The difference between unit, integration, and end-to-end testing.

  • How to design payment test cases.

  • How to test successful and failed transactions.

  • How to test webhooks, refunds, retries, and duplicate requests.

  • How to write automated payment tests using Node.js and Jest.

  • How to use sandbox environments and mock payment providers.

  • How to integrate payment tests into a CI/CD pipeline.

  • Best practices for making payment systems reliable and secure.

Let's get started.

What Is Automated Payment Gateway Integration Testing?

Automated payment gateway integration testing is the process of using automated tests to verify that an application correctly communicates with a payment provider and processes payment-related events.

A payment gateway or payment service provider typically exposes APIs, SDKs, and webhook notifications that allow applications to create payments, confirm transaction outcomes, and process refunds.

Your application must integrate these components correctly.

For example, imagine you are building an online store using Node.js.

When a customer places an order, your application might need to:

  1. Create an order in the database.

  2. Request a payment from the provider.

  3. Handle authentication requirements or payment failures.

  4. Receive confirmation of the payment.

  5. Update the order status.

  6. Send an order confirmation to the customer.

A failure at any stage can create problems.

For example, the payment provider might successfully process a payment while your application fails to update the order because of a network timeout.

Without proper error handling and testing, the customer might see an unsuccessful payment message even though the payment was completed.

Automated integration tests help identify these problems by simulating different outcomes and checking whether the application behaves correctly.

A Simple Payment Testing Example

Suppose your application has a function that processes an order payment.

You might want to verify the following behavior:

Scenario

Expected Result

Payment succeeds

The order becomes paid

Payment is declined

The order is not marked as paid

Payment requires additional authentication

The application handles the next action

Provider request times out

The application does not assume the payment failed

Webhook is delivered twice

The payment is processed only once

Refund succeeds

The refund is recorded correctly

Refund fails

The order and refund records remain consistent

These scenarios represent the kinds of problems automated payment integration tests should cover.

Why Is Payment Gateway Integration Testing Important?

Payment systems handle financial transactions, sensitive information, and business-critical operations.

Even a small bug can lead to duplicate charges, incorrect order statuses, lost revenue, or customer frustration.

Automated testing helps reduce these risks.

1. Prevent Duplicate Payments

Consider a customer who clicks the Pay button twice because the application appears unresponsive.

If both requests create independent payment operations, the customer might be charged more than once.

Automated tests can verify that repeated requests for the same logical payment do not create duplicate charges.

This typically requires server-side idempotency, database constraints, and a clear payment state model—not just disabling the button in the frontend.

2. Handle Payment Failures Correctly

Payments can fail for several reasons:

  • The payment method is declined.

  • The customer fails an authentication challenge.

  • The provider rejects the request.

  • The network connection is interrupted.

  • The payment method requires additional action.

  • The provider experiences a temporary service issue.

Your application must handle each outcome appropriately.

Automated tests help ensure that the application displays useful messages, maintains accurate order records, and avoids unsafe retries.

3. Verify Webhook Processing

Payment providers often send webhooks to notify applications about events such as successful payments, failed payments, and refunds.

Webhooks are important because the browser redirect or API response alone may not provide the final payment outcome.

For example, a customer might close the browser immediately after completing a payment. Your backend should still be able to process the provider's webhook and update the order.

Tests help verify webhook signature validation, event handling, duplicate delivery, and failure recovery.

4. Protect Revenue and Customer Trust

Incorrect payment handling can cause financial discrepancies and support issues.

Automated tests help verify that the application maintains consistent records across orders, payments, refunds, and provider events.

5. Make Deployments Safer

Payment logic often changes when developers add new payment methods, update provider SDKs, or modify checkout workflows.

Automated regression tests help catch problems before changes reach production.

6. Reduce Manual Testing Effort

Manually testing every payment scenario after every code change is slow and repetitive.

A well-designed automated test suite can execute many scenarios consistently whenever the application changes.

Manual testing is still useful for checking real user experiences, device compatibility, and complex authentication flows, but automation handles repeatable scenarios efficiently.

Understanding the Payment Integration Architecture

Before writing tests, it helps to understand how a typical payment integration works.

Consider an application that uses a backend API and a third-party payment provider.

The architecture might look like this:

Customer
   |
   v
Frontend Checkout
   |
   v
Backend API
   |
   +--------------------+
   |                    |
   v                    v
Order Service      Payment Service
                        |
                        v
                Payment Provider API
                        |
                        v
                  Payment Result

Payment Provider
        |
        v
      Webhook
        |
        v
Webhook Handler
        |
        v
Database Update

Each component has a responsibility.

Frontend checkout: Collects customer input and displays payment status.

Backend API: Validates requests and coordinates the checkout workflow.

Order service: Creates and manages customer orders.

Payment service: Communicates with the payment provider and manages payment operations.

Payment provider: Processes the payment according to its own payment methods and transaction rules.

Webhook handler: Receives asynchronous payment events and updates application state.

Database: Stores orders, payment attempts, transaction identifiers, and refund information.

Integration tests should verify that these components work together correctly.

Types of Payment Gateway Tests

A reliable payment test strategy uses several levels of testing.

1. Unit Testing

Unit tests verify individual functions or components in isolation.

For example, you might test a function that calculates the total order amount.

function calculateTotal(items) {
  return items.reduce(
    (total, item) => total + item.price * item.quantity,
    0
  );
}

module.exports = { calculateTotal };

A corresponding Jest test might look like this:

const { calculateTotal } = require("./calculateTotal");

describe("calculateTotal", () => {
  test("calculates the total order amount", () => {
    const items = [
      { price: 100, quantity: 2 },
      { price: 50, quantity: 1 },
    ];

    expect(calculateTotal(items)).toBe(250);
  });
});

This test verifies the calculation without contacting a database or payment provider.

Unit tests are useful for business rules, input validation, fee calculations, and payment-state transition logic.

2. Integration Testing

Integration tests verify that multiple components work together.

For example, a test might verify that:

  1. The payment service creates a payment request.

  2. The provider adapter returns a successful result.

  3. The application records the payment.

  4. The order status changes appropriately.

Depending on the test, the database may be real while the payment provider is mocked, or both the database and provider may be represented by test implementations.

The important distinction is that integration tests validate interactions between components rather than testing one isolated function.

3. End-to-End Testing

End-to-end tests verify a complete customer workflow.

For example:

  1. A customer opens the checkout page.

  2. The customer submits an order.

  3. The application initiates payment.

  4. The test payment method completes the required steps.

  5. The application displays the result.

  6. The backend records the final payment state.

End-to-end tests are useful for verifying the complete user experience, but they are generally slower and more complex than unit or integration tests.

4. Contract Testing

Contract tests verify that your application and payment-provider adapter agree on expected request and response structures.

They can help catch problems when an internal API changes or when provider SDK behavior differs from your assumptions.

For external providers, use their documented schemas, SDKs, and supported test environments rather than inventing responses that do not match the provider's actual contract.

5. Sandbox Testing

A payment sandbox or test environment lets you exercise provider integration behavior without using real customer payments.

Depending on the provider, you may be able to simulate successful payments, declines, refunds, authentication challenges, and other transaction outcomes.

Sandbox testing is especially valuable for verifying the actual provider API contract.

However, a sandbox is not necessarily identical to production. You should also test configuration, deployment, webhook delivery, and operational monitoring.

Setting Up a Payment Testing Environment

A well-isolated test environment makes payment testing safer and more reliable.

For this guide, we will use Node.js, Jest, and a payment-provider abstraction.

The examples use a generic provider interface rather than assuming that every gateway follows the same API.

You can adapt the interface to a provider such as Stripe, Adyen, or another payment service.

Step 1: Create a Node.js Project

Create a project directory:

mkdir payment-integration-tests
cd payment-integration-tests
npm init -y

Install Jest:

npm install --save-dev jest

For an Express-based API, you might also install:

npm install express

If your application uses a database, install the appropriate database driver or ORM separately.

Step 2: Configure Jest

Update the scripts section of package.json:

{
  "scripts": {
    "test": "jest --runInBand"
  }
}

The --runInBand option runs tests serially in one process. It can be useful when tests share a test database or other resources, although isolated tests can often run in parallel.

Step 3: Organize the Project

A simple structure might look like this:

payment-integration-tests/
├── src/
│   ├── paymentService.js
│   ├── paymentProvider.js
│   └── orderRepository.js
├── tests/
│   ├── paymentService.test.js
│   └── paymentWebhook.test.js
├── package.json
└── jest.config.js

As your project grows, you may also add dedicated modules for webhook verification, refund handling, database access, and payment-state transitions.

Creating a Payment Service

Let's create a small payment service that demonstrates the core integration-testing concepts.

The service will:

  • Validate the requested payment amount.

  • Ask the payment provider to create a payment.

  • Record the resulting payment state.

  • Return the result to the caller.

For clarity, this example assumes the order has already been created and that the order repository can retrieve and update it.

In a real application, you should also implement authorization checks, currency validation, database transactions where appropriate, and protection against concurrent payment attempts.

Step 1: Define the Payment Provider Interface

Create src/paymentProvider.js:

class PaymentProvider {
  async createPayment() {
    throw new Error("createPayment() must be implemented");
  }

  async refundPayment() {
    throw new Error("refundPayment() must be implemented");
  }
}

module.exports = PaymentProvider;

This class documents the methods expected from a provider adapter.

Your actual provider implementation would call the payment gateway's SDK or API.

The interface keeps the rest of the application independent of provider-specific request formats.

Step 2: Implement the Payment Service

Create src/paymentService.js:

class PaymentService {
  constructor(provider, orderRepository) {
    this.provider = provider;
    this.orderRepository = orderRepository;
  }

  async createPayment(orderId, amount, currency) {
    if (!Number.isSafeInteger(amount) || amount <= 0) {
      throw new Error("Amount must be a positive integer");
    }

    const order = await this.orderRepository.findById(orderId);

    if (!order) {
      throw new Error("Order not found");
    }

    if (order.status === "paid") {
      throw new Error("Order has already been paid");
    }

    const payment = await this.provider.createPayment({
      orderId,
      amount,
      currency,
    });

    await this.orderRepository.recordPayment({
      orderId,
      providerPaymentId: payment.id,
      status: payment.status,
    });

    return payment;
  }
}

module.exports = PaymentService;

This service uses integer amounts, representing the smallest supported currency unit, such as cents or paise where appropriate.

Currency rules vary, so your application must account for currencies that use different minor-unit conventions.

The service also checks whether the order exists and whether it has already been marked as paid.

However, this check alone is not sufficient to prevent duplicate charges under concurrent requests. Two requests could both pass the check before either updates the order.

Production systems need stronger protections, such as a durable payment-attempt record, a database uniqueness constraint, provider-supported idempotency, and safe coordination of concurrent requests.

Also, a payment result should only be treated as final when its status and the provider's documented payment lifecycle justify that conclusion.

Writing Automated Payment Integration Tests with Jest

Now let's test the payment service.

The goal is to verify that the service sends the correct request to the provider and records the resulting payment state.

Test 1: Successful Payment

Create tests/paymentService.test.js:

const PaymentService = require("../src/paymentService");

describe("PaymentService", () => {
  let provider;
  let orderRepository;
  let paymentService;

  beforeEach(() => {
    provider = {
      createPayment: jest.fn(),
      refundPayment: jest.fn(),
    };

    orderRepository = {
      findById: jest.fn(),
      recordPayment: jest.fn(),
    };

    paymentService = new PaymentService(
      provider,
      orderRepository
    );
  });

  test("creates a payment and records its status", async () => {
    orderRepository.findById.mockResolvedValue({
      id: "order-123",
      status: "pending",
    });

    provider.createPayment.mockResolvedValue({
      id: "payment-123",
      status: "succeeded",
    });

    const result = await paymentService.createPayment(
      "order-123",
      2500,
      "USD"
    );

    expect(provider.createPayment).toHaveBeenCalledWith({
      orderId: "order-123",
      amount: 2500,
      currency: "USD",
    });

    expect(orderRepository.recordPayment).toHaveBeenCalledWith({
      orderId: "order-123",
      providerPaymentId: "payment-123",
      status: "succeeded",
    });

    expect(result.status).toBe("succeeded");
  });
});

This test checks several important behaviors:

  • The order is retrieved before payment creation.

  • The provider receives the expected amount and currency.

  • The returned provider payment ID is recorded.

  • The payment status is passed to the repository.

  • The service returns the provider result.

This is a focused service-level test using mocked dependencies. It does not prove that your database or external provider works correctly.

To verify those integrations, add tests using a real test database and the provider's test environment.

Test 2: Invalid Payment Amount

Your application should reject invalid amounts before calling the payment provider.

Add this test to the same file:

test("rejects a non-positive payment amount", async () => {
  await expect(
    paymentService.createPayment(
      "order-123",
      0,
      "USD"
    )
  ).rejects.toThrow(
    "Amount must be a positive integer"
  );

  expect(provider.createPayment).not.toHaveBeenCalled();
});

This verifies that an invalid amount is rejected before a provider request is made.

You should also test invalid currency codes, unsupported payment methods, and amounts that exceed your application's permitted limits.

Test 3: Order Does Not Exist

Add another test:

test("rejects payment when the order does not exist", async () => {
  orderRepository.findById.mockResolvedValue(null);

  await expect(
    paymentService.createPayment(
      "missing-order",
      2500,
      "USD"
    )
  ).rejects.toThrow("Order not found");

  expect(provider.createPayment).not.toHaveBeenCalled();
});

This ensures that the service does not create a payment for an unknown order.

In a production application, the backend must also verify that the authenticated user is authorized to pay for the specified order.

Test 4: Provider Request Fails

Payment providers may reject requests because of invalid parameters, authentication issues, rate limits, or temporary service failures.

Test how the service handles a provider error:

test("propagates provider errors", async () => {
  orderRepository.findById.mockResolvedValue({
    id: "order-123",
    status: "pending",
  });

  provider.createPayment.mockRejectedValue(
    new Error("Provider request failed")
  );

  await expect(
    paymentService.createPayment(
      "order-123",
      2500,
      "USD"
    )
  ).rejects.toThrow("Provider request failed");

  expect(
    orderRepository.recordPayment
  ).not.toHaveBeenCalled();
});

This test verifies that the repository is not updated as though a successful provider response had been received.

However, there is an important distinction between a definite provider rejection and an uncertain network failure.

A timeout does not necessarily mean that the payment failed. The provider may have processed the request even though your application never received the response.

Production payment systems should represent that uncertainty explicitly and reconcile the result using the provider's supported mechanisms.

Testing Failed and Pending Payments

Not every payment succeeds immediately.

Your application should handle different payment states instead of assuming that every provider response means success or failure.

Depending on the provider, a payment may be:

  • Successful.

  • Pending.

  • Processing.

  • Declined or failed.

  • Awaiting additional customer authentication.

  • Canceled.

  • Refunded or partially refunded.

The exact states and transitions depend on the payment provider.

Test 5: Declined Payment

Suppose the provider returns a definitive failed status.

test("records a declined payment", async () => {
  orderRepository.findById.mockResolvedValue({
    id: "order-123",
    status: "pending",
  });

  provider.createPayment.mockResolvedValue({
    id: "payment-456",
    status: "failed",
  });

  const result = await paymentService.createPayment(
    "order-123",
    2500,
    "USD"
  );

  expect(result.status).toBe("failed");

  expect(orderRepository.recordPayment).toHaveBeenCalledWith({
    orderId: "order-123",
    providerPaymentId: "payment-456",
    status: "failed",
  });
});

This verifies that the application records the returned status rather than assuming every created payment succeeded.

In a real implementation, use the provider's documented statuses and map them to your application's internal payment states.

Test 6: Pending Payment

Some payment methods take time to complete.

For example, a customer might need to approve a bank payment or complete an authentication step.

Your application should not mark an order as paid simply because a payment request was created.

A basic test might look like this:

test("preserves a pending payment status", async () => {
  orderRepository.findById.mockResolvedValue({
    id: "order-123",
    status: "pending",
  });

  provider.createPayment.mockResolvedValue({
    id: "payment-789",
    status: "processing",
  });

  const result = await paymentService.createPayment(
    "order-123",
    2500,
    "USD"
  );

  expect(result.status).toBe("processing");

  expect(orderRepository.recordPayment).toHaveBeenCalledWith({
    orderId: "order-123",
    providerPaymentId: "payment-789",
    status: "processing",
  });
});

The test confirms that the processing status is preserved.

A production system should also define what happens next, including which webhook events or provider queries can move the payment into a final state.

Testing Duplicate Payment Requests and Idempotency

Duplicate payment requests are among the most important scenarios to test.

Imagine a customer clicks the Pay button, but the browser does not receive a response quickly enough.

The frontend sends the request again.

If your backend creates a new payment for every request, the customer could be charged twice.

What Is Idempotency?

An operation is idempotent when repeating it with the same logical request does not produce additional unintended effects.

Payment providers commonly support idempotency keys for certain API operations.

When the same key is reused according to the provider's rules, the provider can return the result associated with the original request rather than creating another payment operation.

Your application should also track payment attempts and prevent duplicate processing at its own boundary.

Example Idempotency Test

Suppose your provider adapter accepts an idempotency key.

A simplified test could look like this:

test("uses the same idempotency key for a retry", async () => {
  const provider = {
    createPayment: jest.fn()
      .mockResolvedValueOnce({
        id: "payment-123",
        status: "processing",
      })
      .mockResolvedValueOnce({
        id: "payment-123",
        status: "processing",
      }),
  };

  const idempotencyKey = "order-123-payment-attempt-1";

  await provider.createPayment({
    orderId: "order-123",
    amount: 2500,
    currency: "USD",
    idempotencyKey,
  });

  await provider.createPayment({
    orderId: "order-123",
    amount: 2500,
    currency: "USD",
    idempotencyKey,
  });

  expect(provider.createPayment).toHaveBeenNthCalledWith(
    1,
    expect.objectContaining({
      idempotencyKey,
    })
  );

  expect(provider.createPayment).toHaveBeenNthCalledWith(
    2,
    expect.objectContaining({
      idempotencyKey,
    })
  );
});

This test verifies that the same key is passed on both attempts.

It does not prove that a real provider deduplicates the requests. Because the provider is mocked, the test only checks your application's behavior.

For stronger verification, use the provider's test environment and follow its idempotency documentation.

Important Idempotency Rules

  • Generate and persist an idempotency key for a logical payment attempt.

  • Reuse the same key when retrying that attempt.

  • Do not generate a new key for every network retry.

  • Do not reuse the same key for unrelated payments.

  • Persist enough information to recover after an application restart.

  • Enforce appropriate database constraints to prevent duplicate internal payment records.

A simple key based on an order ID may not be enough if an order can legitimately have multiple payment attempts. Design the key around the identity of the specific logical operation.

Testing Payment Webhooks

Webhooks are a critical part of payment integration testing.

A payment provider may send a webhook when a payment succeeds, fails, or changes state.

Your backend receives the event and updates the application's records.

For example:

Payment Provider
       |
       v
POST /webhooks/payments
       |
       v
Verify Webhook Signature
       |
       v
Check Event and Payment Status
       |
       v
Deduplicate Event
       |
       v
Update Payment and Order
       |
       v
Return Successful HTTP Response

A robust webhook handler should verify the provider's signature, process events safely, and handle repeated deliveries.

Why Webhooks Need Special Testing

Webhook delivery can be delayed, duplicated, or temporarily unsuccessful.

Events may also arrive in an order different from the order in which your application expected them.

Your application must handle these cases without incorrectly marking an order as paid or refunding it twice.

Example Webhook Handler

The following example demonstrates the general structure of a webhook handler.

It uses an abstract verifier and repository so that the code does not depend on a particular provider's signature format.

Create src/paymentWebhook.js:

function createPaymentWebhook({
  verifier,
  paymentRepository,
}) {
  return async function handleWebhook(request) {
    const event = verifier.verify(
      request.rawBody,
      request.signature
    );

    const result = await paymentRepository.applyEventOnce(
      event
    );

    return {
      received: true,
      duplicate: result.duplicate,
    };
  };
}

module.exports = createPaymentWebhook;

This example assumes that:

  • verifier.verify() validates the signature using the provider's documented verification mechanism.

  • applyEventOnce() atomically deduplicates the event and applies its effects.

The actual implementation depends on the provider and database.

For example, an event repository can use a unique constraint on the provider's event ID. Recording the event and applying the payment-state update should be designed so that a failed transaction does not permanently mark an event as processed before its effects have been saved.

Do not implement webhook signature verification by simply trusting an event ID or parsing arbitrary JSON from an incoming request.

Test 7: Valid Webhook

Create tests/paymentWebhook.test.js:

const createPaymentWebhook = require("../src/paymentWebhook");

describe("Payment webhook", () => {
  test("processes a verified event", async () => {
    const event = {
      id: "event-123",
      type: "payment.succeeded",
      paymentId: "payment-123",
    };

    const verifier = {
      verify: jest.fn().mockReturnValue(event),
    };

    const paymentRepository = {
      applyEventOnce: jest.fn().mockResolvedValue({
        duplicate: false,
      }),
    };

    const handleWebhook = createPaymentWebhook({
      verifier,
      paymentRepository,
    });

    const result = await handleWebhook({
      rawBody: Buffer.from("{}"),
      signature: "test-signature",
    });

    expect(verifier.verify).toHaveBeenCalled();

    expect(
      paymentRepository.applyEventOnce
    ).toHaveBeenCalledWith(event);

    expect(result).toEqual({
      received: true,
      duplicate: false,
    });
  });
});

This test verifies that the handler passes the raw body and signature to the verifier before processing the event.

Because the verifier is mocked, this does not test the provider's actual cryptographic signature verification.

Add provider-specific tests to confirm that valid signatures are accepted and invalid signatures are rejected.

Test 8: Duplicate Webhook

Providers may deliver the same event more than once.

Your system should not repeat the event's business effects.

test("does not reapply a duplicate event", async () => {
  const event = {
    id: "event-123",
    type: "payment.succeeded",
    paymentId: "payment-123",
  };

  const verifier = {
    verify: jest.fn().mockReturnValue(event),
  };

  const paymentRepository = {
    applyEventOnce: jest.fn().mockResolvedValue({
      duplicate: true,
    }),
  };

  const handleWebhook = createPaymentWebhook({
    verifier,
    paymentRepository,
  });

  const result = await handleWebhook({
    rawBody: Buffer.from("{}"),
    signature: "test-signature",
  });

  expect(result.duplicate).toBe(true);

  expect(
    paymentRepository.applyEventOnce
  ).toHaveBeenCalledTimes(1);
});

This verifies the handler's interaction with the deduplication layer.

To fully test duplicate-event behavior, add integration tests against your real test database. Those tests should send the same event more than once and verify that the database records only one effective payment-state transition.

Testing Refunds

Refunds are another important part of payment integration testing.

A refund workflow may involve:

  1. Identifying the original payment.

  2. Verifying the refundable amount.

  3. Requesting a refund from the provider.

  4. Recording the refund attempt.

  5. Handling the provider's response.

  6. Updating the payment and order records.

Refunds may be full or partial, and their processing can be asynchronous.

A successful refund API request does not necessarily mean the customer's bank has completed the entire refund process. Use the provider's documented status model.

Refund Test Cases

Test Scenario

Expected Result

Full refund succeeds

Refund is recorded and status is updated

Partial refund succeeds

The refunded amount is recorded accurately

Refund exceeds the refundable amount

The request is rejected

Refund request fails

The failure is recorded without falsely marking the refund complete

Duplicate refund request

The same logical refund is not applied twice

Refund webhook arrives

The refund state is reconciled correctly

Example Refund Test

Suppose your payment service calls the provider's refund method.

test("requests a refund from the provider", async () => {
  provider.refundPayment.mockResolvedValue({
    id: "refund-123",
    status: "succeeded",
  });

  const result = await provider.refundPayment({
    paymentId: "payment-123",
    amount: 2500,
  });

  expect(provider.refundPayment).toHaveBeenCalledWith({
    paymentId: "payment-123",
    amount: 2500,
  });

  expect(result.status).toBe("succeeded");
});

This simple example verifies the expected provider call.

A complete integration test should also check that the application validates the refundable balance, persists the refund record, handles asynchronous outcomes, and prevents duplicate refund operations.

Testing Network Failures and Timeouts

Network failures are particularly challenging in payment systems.

Imagine your backend sends a payment request to the provider.

The provider processes the payment, but the network connection fails before your application receives the response.

Your application now has an uncertain outcome.

If it blindly creates another payment, the customer could be charged twice.

What Should Your Application Do?

A safer workflow is:

  1. Record the payment attempt before calling the provider.

  2. Use a stable idempotency key for the logical operation.

  3. Send the payment request.

  4. If the response is uncertain, mark the attempt as pending or requiring reconciliation.

  5. Query the provider or wait for an authenticated webhook, where supported.

  6. Retry safely only according to the provider's documented behavior.

  7. Update the internal state when the outcome is known.

The application should not automatically interpret every timeout as a failed payment.

Example Timeout Test

A simple unit test can simulate a provider timeout:

test("handles an uncertain provider response", async () => {
  orderRepository.findById.mockResolvedValue({
    id: "order-123",
    status: "pending",
  });

  provider.createPayment.mockRejectedValue(
    new Error("Request timed out")
  );

  await expect(
    paymentService.createPayment(
      "order-123",
      2500,
      "USD"
    )
  ).rejects.toThrow("Request timed out");
});

This test verifies how the current simplified service behaves when the provider throws an error.

It does not implement a complete timeout-recovery strategy. In production, you should distinguish definitive provider errors from uncertain outcomes and persist enough information to reconcile them later.

Testing Database Consistency

A payment integration can call the provider successfully and still fail to update the database.

For example:

  1. The payment provider confirms a successful payment.

  2. The backend tries to update the order.

  3. The database connection fails.

  4. The application has a successful provider payment but an outdated order record.

This can create inconsistencies between the provider's transaction records and your application's database.

Integration tests should verify that the system can recover from these situations.

Important Database Test Scenarios

Test whether:

  • Payment attempts are recorded correctly.

  • Provider transaction IDs are stored.

  • Duplicate payment records are prevented.

  • Order state changes are applied consistently.

  • Failed database writes can be retried safely.

  • Webhook events can be reprocessed after transient failures.

  • Refund amounts match the provider's confirmed outcomes.

  • Concurrent requests cannot create conflicting payment states.

For database integration tests, use a dedicated test database and reset its state between tests.

Do not run destructive tests against a production database.

Use Database Transactions Carefully

Transactions can help maintain consistency among your application's own database records.

However, a database transaction cannot automatically roll back a payment already processed by an external provider.

Because the database and payment provider are separate systems, payment workflows often require durable payment attempts, idempotency, asynchronous reconciliation, and carefully designed state transitions.

Do not assume that wrapping database statements in BEGIN and COMMIT makes the entire external payment workflow atomic.

Building a Comprehensive Payment Test Matrix

A test matrix helps ensure that important payment scenarios are covered.

Here is a practical example.

Category

Scenario

Expected Behavior

Payment creation

Valid payment request

Payment attempt is created

Payment creation

Invalid amount

Request is rejected

Payment creation

Unknown order

No provider payment is created

Payment result

Payment succeeds

Payment state is updated correctly

Payment result

Payment is declined

Order is not marked as paid

Payment result

Payment is pending

Order remains in an appropriate pending state

Authentication

Additional authentication required

Customer can complete the required step

Idempotency

Same request is retried

Duplicate charge is avoided

Webhooks

Valid signature

Event is accepted

Webhooks

Invalid signature

Event is rejected

Webhooks

Duplicate event

Business effects are applied only once

Webhooks

Temporary database failure

Event can be retried safely

Refunds

Full refund

Correct amount and state are recorded

Refunds

Partial refund

Partial amount is recorded accurately

Refunds

Duplicate request

Refund is not duplicated

Network

Provider timeout

Outcome is reconciled safely

Database

Write failure after payment

System can recover without losing track of the payment

Security

Sensitive data appears in logs

Sensitive data is redacted

Configuration

Test credentials are used

No real payment is created

Use this matrix as a starting point, then adapt it to the provider and payment methods your application supports.

Using a Payment Gateway Sandbox

A sandbox is a test environment provided by a payment service that allows developers to exercise payment-related workflows without using real customer funds.

Many payment providers supply test credentials and simulated payment methods.

For example, a provider may allow you to simulate:

  • Successful payments.

  • Declined payments.

  • Authentication requirements.

  • Refunds.

  • Payment status changes.

  • Webhook events.

The available scenarios depend on the provider.

How to Set Up a Sandbox

A typical setup involves the following steps:

Step 1: Create a test account.

Register for the provider's developer or test environment.

Step 2: Obtain test credentials.

Use the credentials specifically issued for testing.

Step 3: Configure the test environment.

Set up the test API endpoint, webhook endpoint, and supported payment methods.

Step 4: Store configuration securely.

Use environment variables or a secrets-management system rather than committing credentials to source control.

Step 5: Run test scenarios.

Exercise successful payments, failures, timeouts, refunds, and webhook events.

Step 6: Verify the results.

Check your application's database, provider test dashboard, logs, and webhook records.

Step 7: Keep test and production environments separate.

Make sure test credentials and endpoints cannot accidentally be used to initiate real transactions, and production credentials are not exposed to test environments.

For provider-specific setup instructions, consult the provider's official documentation.

Mocking vs. Real Sandbox Integration Tests

Mocks and sandbox tests serve different purposes.

Mock-Based Tests

Mock-based tests replace the real provider with a test implementation.

They are useful for:

  • Testing business logic.

  • Simulating rare failures.

  • Testing retry behavior.

  • Verifying the parameters sent to the provider adapter.

  • Running fast and predictable tests in CI.

However, mocks cannot prove that your request matches the provider's actual API or that the provider will respond as expected.

Sandbox Integration Tests

Sandbox tests communicate with the provider's actual test environment.

They are useful for:

  • Verifying request and response compatibility.

  • Testing real provider SDK integration.

  • Confirming webhook setup.

  • Exercising supported payment states.

  • Checking provider-specific authentication flows.

Sandbox tests can be slower, may depend on network availability, and may be subject to provider rate limits.

Recommended Strategy

Use both approaches.

Run fast, mock-based tests frequently, including on every relevant code change.

Run a smaller set of provider sandbox tests in a controlled CI stage or scheduled validation process.

Keep end-to-end tests focused on the most important customer journeys.

This approach provides a balance between speed, reliability, and realistic integration coverage.

Automating Payment Tests in CI/CD

Continuous Integration and Continuous Deployment (CI/CD) pipelines allow teams to run automated tests whenever code changes.

Payment tests should be part of this process because payment-related bugs can have serious consequences.

A typical pipeline might look like this:

Developer Pushes Code
        |
        v
Install Dependencies
        |
        v
Run Linting and Static Checks
        |
        v
Run Unit Tests
        |
        v
Run Integration Tests
        |
        v
Run Payment Sandbox Tests
        |
        v
Review Results
        |
        v
Deploy to Staging
        |
        v
Production Release

The exact stages depend on your project.

Example GitHub Actions Workflow

The following workflow runs Jest tests using Node.js.

Create .github/workflows/test.yml:

name: Automated Tests

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run automated tests
        run: npm test

This is an illustrative workflow. Use supported action versions and a Node.js version compatible with your project.

The workflow runs the test command defined in package.json.

For database integration tests, you can add a dedicated PostgreSQL service or another isolated test database.

For provider sandbox tests, configure the required test credentials through your CI platform's secrets mechanism. Do not expose production payment credentials to ordinary test jobs.

A production deployment should also have appropriate review, monitoring, and rollback procedures.

Security Best Practices for Payment Integration Testing

Payment tests should validate security behavior as well as transaction functionality.

1. Never Use Real Customer Payment Details in Tests

Use provider-approved test credentials and synthetic test data.

Avoid storing actual card details, CVVs, or other sensitive payment information in test fixtures.

2. Protect API Credentials

Do not hard-code secret keys in your tests or commit them to source control.

Use restricted test credentials and secure environment configuration.

3. Verify Webhook Signatures

Your webhook handler should validate incoming events using the provider's documented signature-verification method.

Reject invalid signatures before processing the event.

4. Redact Sensitive Information from Logs

Logs are useful for debugging payment failures, but they should not expose secret keys, authorization headers, or sensitive payment data.

Record relevant transaction IDs, event IDs, timestamps, and sanitized error information instead.

5. Test Authorization

Verify that users cannot pay for orders they do not own, access other customers' payment records, or initiate unauthorized refunds.

These checks should be enforced by the backend, not just the frontend.

6. Test Idempotency

Verify that retries and repeated webhook deliveries do not create duplicate charges, refunds, or order updates.

7. Understand Your PCI DSS Responsibilities

The Payment Card Industry Data Security Standard (PCI DSS) applies to organizations and systems according to their role in handling payment account data.

Using a hosted checkout or provider SDK may reduce some compliance responsibilities, but it does not automatically remove every PCI DSS obligation.

Follow your provider's integration guidance and obtain appropriate compliance advice for your payment architecture.

Common Mistakes in Automated Payment Testing

Avoid these common mistakes when building your test suite.

Testing only successful payments: Real systems must handle declines, pending transactions, timeouts, refunds, and authentication requirements.

Relying entirely on mocks: Mocks cannot validate the real provider's API contract.

Assuming a timeout means failure: The provider may have processed the payment even if the application never received the response.

Ignoring duplicate webhooks: Providers may retry event delivery. Your system should handle repeated events safely.

Failing to test database recovery: A provider payment can succeed even when a local database update fails.

Using real payment credentials in CI: Keep automated tests isolated from production payment systems.

Retrying every request with a new idempotency key: This may create multiple payment operations instead of retrying the original logical operation.

Marking an order as paid too early: Creating a payment request is not the same as confirming a successful payment.

Testing implementation details instead of outcomes: Tests should verify important business behavior, not merely that a particular method was called.

Ignoring asynchronous payment states: Some payment methods require additional authentication or take time to complete.

Avoiding these mistakes will help make your payment test suite more reliable.

Frequently Asked Questions (FAQs)

1. What is automated payment gateway integration testing?

Automated payment gateway integration testing verifies that an application communicates correctly with a payment provider and handles transaction outcomes, webhooks, refunds, errors, and database updates as expected.

2. Why is payment gateway testing important?

It helps prevent duplicate charges, incorrect order statuses, refund errors, and inconsistencies between your application and the payment provider. It also helps identify integration problems before production deployment.

3. Can I test payment gateways without real money?

Yes. Many payment providers offer sandbox or test environments with simulated payment methods and transaction outcomes. These environments allow you to test supported payment workflows without processing real customer payments.

4. What is the difference between payment unit testing and integration testing?

Unit testing verifies individual functions in isolation, often using mocks. Integration testing checks how multiple components work together, such as a payment service, database, and provider adapter. End-to-end testing verifies a complete customer workflow.

5. How do I test failed payments?

Use the payment provider's test environment or a mock provider to simulate documented failure scenarios. Verify that the application records the appropriate state, displays a clear message, and does not mark the order as paid.

6. How do I prevent duplicate payments?

Use provider-supported idempotency keys, durable payment-attempt records, database constraints, and safe concurrency handling. Also ensure that retrying a logical payment operation does not create an unrelated payment request.

7. How should I test payment webhooks?

Test valid and invalid signatures, duplicate events, delayed events, unexpected event ordering, and temporary database failures. Verify that the handler processes each event safely and can recover from failures.

8. Can Jest be used for payment gateway integration tests?

Yes. Jest can test payment services, provider adapters, webhook handlers, and other backend components. You can use mocks for fast tests and connect to a dedicated test database or provider sandbox for deeper integration testing.

9. Should payment integration tests run in CI/CD?

Yes. Unit and integration tests should generally run automatically during development and CI. Sandbox tests can run in a dedicated stage or on a controlled schedule, depending on provider limitations and execution time.

10. How do I test refunds?

Test full and partial refunds, invalid refund amounts, provider failures, duplicate refund requests, asynchronous refund updates, and consistency between your application and the provider's records.

11. What happens if a payment succeeds but the database update fails?

The application may temporarily have inconsistent records. A reliable system should persist payment attempts, reconcile uncertain outcomes using provider-supported APIs or webhooks, and safely retry database updates without creating another charge.

12. Which tools can I use for automated payment testing?

Common tools include Jest or another test framework for application logic, provider sandbox environments for API testing, a dedicated test database for persistence checks, and CI/CD platforms for automatically running tests. The right combination depends on your application and payment provider.

Conclusion

Automated payment gateway integration testing is essential for building reliable payment systems.

A payment workflow involves much more than sending a request to a provider. Your application must handle successful and failed transactions, asynchronous webhooks, duplicate requests, network timeouts, refunds, database consistency, and security requirements.

By combining unit tests, integration tests, sandbox validation, and end-to-end tests, you can catch problems earlier and reduce the risk of payment-related failures.

If you are building a Node.js application, start by testing your payment service with Jest. Then add integration tests for database persistence, webhook verification, idempotency, and refunds.

Finally, connect a controlled set of tests to your CI/CD pipeline so that important payment behavior is verified whenever the code changes.

The goal is not simply to prove that a payment can succeed. It is to prove that your application behaves correctly when payments succeed, fail, time out, repeat, or require recovery.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘