# Testing

Test your Aeropay integration before accepting live payments or payouts.

## Overview

Test the complete Aeropay journey, including component configuration, new and returning shoppers, OTP verification, bank linking, every supported intent, transaction failures, and backend verification.

Use `environment: "test"` with UAT credentials and test data. Don't use production Aeropay credentials, real bank accounts, or real shopper data during development.

Get approved UAT users, OTP behaviour, bank account scenarios, and expected provider responses from your PXP or Aeropay integration contact.

## Test environment

Initialise the SDK with a UAT session and matching test transaction data:

```typescript
const pxpSdk = PxpCheckout.initialize({
  environment: 'test',
  session: sessionResult.session,
  ownerId: 'MERCHANT_GROUP_1',
  ownerType: 'MerchantGroup',
  transactionData: {
    currency: 'USD',
    amount: 10,
    entryType: 'Ecom',
    intent: {
      aeropay: IntentType.Authorisation
    },
    merchantTransactionId: sessionResult.merchantTransactionId,
    merchantTransactionDate: () => new Date().toISOString()
  },
  onGetShopper: async () => ({
    id: 'test-shopper-1',
    firstName: 'Test',
    lastName: 'Shopper',
    email: 'test.shopper@example.com',
    phoneNumber: '+14155550123'
  }),
  analyticsEvent: (event) => {
    console.log('[Aeropay analytics]', event.eventName, event);
  }
});
```

Use environment settings consistently:

| SDK environment | Aeropay and Aerosync configuration | Purpose |
|  --- | --- | --- |
| `test` | UAT or sandbox configuration | Development, automated testing, and UAT |
| `live` | Production configuration | Live payments and payouts |


Confirm which credentials and test identities apply to each environment before testing.

## Add diagnostic callbacks

Use callbacks to trace the flow without logging personal or bank data:

```typescript
const aeropayButton = pxpSdk.create('aeropay-button', {
  onClick: () => {
    console.log('[Aeropay] Button clicked');
  },
  onUserVerificationSuccess: () => {
    console.log('[Aeropay] User verified');
  },
  onCancel: () => {
    console.log('[Aeropay] Popup close button used');
  },
  onPreAuthorisation: () => {
    console.log('[Aeropay] Pre-authorisation');
    return true;
  },
  onPostAuthorisation: (result) => {
    const submitResult = result as {
      merchantTransactionId: string;
      systemTransactionId: string;
    };
    console.log('[Aeropay] Transaction submitted', {
      merchantTransactionId: submitResult.merchantTransactionId,
      systemTransactionId: submitResult.systemTransactionId
    });
  },
  onSubmitError: (error) => {
    console.error('[Aeropay] Submission error', error);
  },
  onError: (error) => {
    console.error('[Aeropay] Flow error', {
      errorCode: error.ErrorCode,
      message: error.message
    });
  }
});
```

Don't log shopper details, OTPs, Aeropay user IDs, bank account IDs, credentials, or complete provider responses.

## Configuration tests

Test each required configuration rule before testing the shopper flow:

| Scenario | Expected result |
|  --- | --- |
| Valid Aeropay-enabled session | The component is created and the button mounts. |
| Missing `externalMerchantId` | `pxpSdk.create()` throws `SDK0113`. |
| Missing `configurationId` | `pxpSdk.create()` throws `SDK0113`. |
| Missing Aeropay intent | `pxpSdk.create()` throws `SDK0115`. |
| Unsupported intent | `pxpSdk.create()` throws `SDK0106`. |
| Entry type other than `Ecom` | `pxpSdk.create()` throws `SDK0114`. |
| Currency other than `USD` | `pxpSdk.create()` throws `SDK0116`. |
| Missing mount container | `mount()` throws `SDK0201`. |


For example, confirm that an unsupported currency fails during component creation:

```typescript
const invalidSdk = PxpCheckout.initialize({
  ...validSdkConfig,
  transactionData: {
    ...validSdkConfig.transactionData,
    currency: 'GBP'
  }
});

try {
  invalidSdk.create('aeropay-button', {
    onPreAuthorisation: () => true
  });
} catch (error) {
  console.log((error as { ErrorCode?: string }).ErrorCode);
  // Expected: SDK0116
}
```

## Component tests

Verify basic button behaviour:

* The Aeropay logo and default payment label render for payment intents.
* The localised payout label renders when the intent is `Payout`. Custom `label` doesn't override that payout wording.
* For payment intents, custom `label`, `className`, and `styles` values are applied.
* Hover, disabled, loading, and focus states remain readable.
* `setDisabled(true)` prevents the flow from starting.
* `hide()` and `show()` update visibility.
* Repeated clicks while `onGetShopper` is pending can open multiple popups. Prevent repeat interaction until the callback resolves, or track this as a known defect.
* `unmount()` removes the button, popup resources, and event listeners.


Test the button at mobile, tablet, and desktop viewport sizes.

## New-shopper tests

### No prefilled data

Omit `onGetShopper` or return only a shopper ID. Confirm that:

1. The consumer data screen opens with empty fields.
2. All four fields are editable and required.
3. Inline errors appear for empty or invalid values.
4. Valid data advances to OTP verification.
5. Successful OTP verification calls `onUserVerificationSuccess`.
6. Bank selection opens after verification.


### Partial prefilled data

Return some consumer fields:

```typescript
onGetShopper: async () => ({
  id: 'test-shopper-2',
  firstName: 'Test',
  email: 'test.shopper@example.com'
})
```

Confirm that provided fields are prefilled and disabled, while missing fields remain empty and editable.

### Editable prefilled data

Make selected fields editable:

```typescript
const aeropayButton = pxpSdk.create('aeropay-button', {
  consumerDataCollectionConfig: {
    editableFields: ['email']
  },
  onPreAuthorisation: () => true
});
```

Confirm that only the configured fields can be changed and that edited values still receive validation.

### Skip consumer data collection

Return all four valid consumer fields and set `skipConsumerDataCollection` to `true`:

```typescript
const aeropayButton = pxpSdk.create('aeropay-button', {
  skipConsumerDataCollection: true,
  onPreAuthorisation: () => true
});
```

Confirm that the SDK creates the user in the background and opens OTP verification directly.

Also test that the data screen still appears when:

* A required field is missing or empty.
* `consumerDataCollectionConfig.editableFields` contains a value.


If a supplied field is invalid, confirm that `onError` receives `SDK1300` and the popup doesn't open.

## Consumer data tests

Test valid, missing, boundary, and invalid values:

| Field | Valid examples | Invalid or boundary examples |
|  --- | --- | --- |
| First name | `Test`, `María`, `Test User` | Empty, more than 100 characters, `Test-User`, `Test2` |
| Last name | `Shopper`, `García`, `Test Shopper` | Empty, more than 100 characters, `O'Neil`, `Shopper2` |
| Email | `test@example.com` | Empty, missing `@`, missing domain dot, whitespace, more than 128 characters |
| Phone number from `onGetShopper` | `+14155550123` | Empty when skipping, missing `+1`, too few or too many digits, formatting characters |
| Phone number entered in the form | `4155550123` | Empty, fewer or more than 10 digits |


The current name rules accept Unicode letters and spaces only. Test real customer-name patterns against this limitation before launch.

## OTP tests

Test the OTP screen with provider-approved UAT scenarios:

* Confirm that **Verify code** remains disabled until all six-digit cells contain a value.
* Confirm that typed or pasted non-digit characters are filtered out.
* Exercise empty, incomplete, non-digit, and malformed values directly in defensive validation tests.
* Test an incorrect six-digit code.
* Test a correct six-digit code.
* Test an expired code, if your UAT setup supports it.
* Try to resend while the 59-second countdown is active.
* Resend successfully after the countdown.
* Test the provider's maximum-attempt response.
* Test a network failure during verification or resend.


Confirm that maximum attempts disable both verification and resend actions for the current flow.

## Bank selection and Aerosync tests

Test bank account loading, selection, and linking:

| Scenario  | Expected result |
|  --- | --- |
| One or more linked accounts | Accounts load and the component selects the provider-selected account, or the first account if the provider hasn't selected one. |
| No linked accounts | The component shows the empty state and offers bank linking for payment flows. |
| Select a different account | The selected indicator moves and only one account remains selected. |
| `excludedBankAccountIds` includes one or more linked account IDs | Matching accounts don't appear in the bank selection list. Comparisons use string equality after normalising ID values. |
| Link a new account | Aerosync opens, completes, and the linked account appears. |
| Close Aerosync before completion | Loading clears and the shopper can retry. |
| Invalid Aerosync payload | `onError` receives `SDK1303`. |
| Aerosync provider error | `onError` receives `SDK1304`. |
| Link-account API failure | `onError` receives `SDK1305`. |
| Bank-account retrieval failure | `onError` receives `SDK1306`. |


Test both `aerosyncTheme: "light"` and `"dark"` if your integration allows the theme to vary.

## Returning-shopper tests

Test `userId` with these scenarios:

| Scenario | Expected result |
|  --- | --- |
| Valid active user | Consumer data and OTP are skipped, and bank selection opens. |
| Truthy non-string value at runtime | `onError` receives `SDK1310`. |
| Falsy value, including an empty string | The component treats the value as absent and starts the new-shopper flow. Whether it shows consumer data collection depends on the prefilled data and skip configuration. |
| Inactive user | `onError` receives `SDK1307`. |
| User lookup failure | `onError` receives `SDK1308`. |
| User not found | `onError` receives `SDK1309`. |


Confirm that your application removes an invalid stored ID and offers the new-shopper flow.

## Transaction tests

Run end-to-end tests for every intent enabled for your account:

* `Authorisation`
* `Purchase`
* `EstimatedAuthorisation`
* `Payout`


For each intent, verify:

1. Your backend confirms that the session and SDK transaction data represent the intended contract, including the intent, amount, currency, and `merchantTransactionId`. This is an integration check, not browser SDK validation that every session and SDK value matches.
2. `onPreAuthorisation` runs before submission.
3. Returning `false` prevents submission.
4. Returning `true` allows submission.
5. A successful submission calls `onPostAuthorisation`.
6. A failed submission calls `onSubmitError`.
7. Your backend retrieves and validates the authoritative transaction.
8. Your application updates the order or payout only after backend verification.


### Post-transaction scenarios

Use Unity Portal *Reporting* actions to test the applicable post-transaction lifecycle:

* Capture a successful `Authorisation` or `EstimatedAuthorisation`.
* Increment an eligible authorisation, then confirm that the final captured amount is correct.
* Void an eligible transaction before capture.
* Refund a captured `Authorisation` or completed `Purchase`.
* Confirm that `Purchase` completes payment without a separate capture operation.


For each action, find the transaction in *Reporting* by its `merchantTransactionId` or `systemTransactionId`, open its details, perform the available action, and confirm the updated amount and status. Available actions depend on the transaction intent and current state.

### Payout scenarios

Test payouts with an existing linked account and with no linked accounts.

Confirm that:

* The button and confirmation action use payout wording.
* Bank linking is hidden when `allowLinkBankOnPayout` is `false` or omitted.
* Bank linking appears when `allowLinkBankOnPayout` is `true`.
* Payout eligibility and limits are validated on your backend.
* The verified PXP result matches the intended recipient, amount, currency, and state.


## Cancellation and recovery tests

Confirm that using the popup close button:

* Calls `onCancel`.
* Removes loading indicators.
* Keeps the checkout usable.
* Doesn't show a payment-failure message.
* Lets the shopper restart the flow.


Pressing Escape currently hides the popup without calling `onCancel`. Test this behaviour separately and make sure your checkout remains usable after the popup closes.

Also test browser refresh, route changes, session expiry, slow networks, offline transitions, and repeated clicks.

## Analytics tests

Enable temporary event logging and verify the events expected for each flow:

```typescript
analyticsEvent: (event) => {
  console.log('[Aeropay analytics]', event.eventName, event);
}
```

Check these core events:

| Event | Scenario |
|  --- | --- |
| `ComponentInteraction` | Button clicks, form submissions, OTP interactions, and popup closure |
| `AerosyncLaunched` | Bank-linking widget opened |
| `AerosyncCompleted` | Bank linking completed |
| `AerosyncFailed` | The Aerosync widget reports an error. The SDK also invokes `onError`. |
| `PreAuthorisation` | `onPreAuthorisation` configured and transaction confirmed |
| `PostAuthorisation` | Successful submission with `onPostAuthorisation` configured |
| `ComponentError` | SDK, Aeropay API, bank-account, or transaction error. A direct Aerosync widget error doesn't emit this event. |
| `ErrorMessageShown` | Inline validation or flow error displayed |


Confirm that forwarded analytics don't contain shopper details, OTPs, user IDs, bank metadata, credentials, or sensitive URL parameters.

## Accessibility tests

Test the complete flow using:

* Keyboard-only operation
* A supported screen reader
* Browser zoom at 200%
* High-contrast or forced-colour settings where applicable
* Mobile and desktop viewport sizes


Confirm that focus remains visible, labels are announced, errors are associated with their fields, disabled controls are communicated, and the popup close control is accessible.

## Pre-launch checklist

Before switching to production, complete these checks.

### Configuration

- Confirm that the production Aeropay service is active for the correct site.
- Confirm that production credentials and the configuration ID are saved securely.
- Confirm that sessions contain `externalMerchantId` and `configurationId`.
- Confirm that the currency is `USD` and the entry type is `Ecom`.
- Confirm on your backend that session and SDK transaction data represent the intended transaction contract. Don't treat this as browser SDK validation that every value must match.


### Shopper flows

- Confirm that new shoppers can complete data collection and OTP verification.
- Confirm that partial and full prefill behave correctly.
- Confirm that returning shoppers skip verification only with a valid active user.
- Confirm that invalid stored user IDs recover to the new-shopper flow.
- Confirm that stored Aeropay user IDs are retrieved for the authenticated customer and can't be supplied or changed by the browser.
- Confirm that bank account selection and Aerosync linking work.


### Transactions

- Confirm that every enabled payment intent has an end-to-end UAT result.
- Test each applicable capture, increment, void, and refund action in the Unity Portal's *Reporting* section.
- Confirm that `Purchase` doesn't require a separate capture operation.
- Test payout scenarios and controls, if applicable.
- Confirm that your backend validates payout eligibility, amount limits, account status, and duplicate requests.
- Confirm that `onPreAuthorisation` stops and allows submission correctly.
- Confirm that submission failures provide a safe retry or alternative method.
- Confirm that backend verification prevents fulfilment from unverified callbacks.


### Security and operations

- Confirm that no credentials or personal data appear in frontend logs or analytics.
- Confirm that your checkout doesn't collect routing numbers or full bank account numbers.
- Confirm that HTTPS is enabled for production checkout and backend endpoints.
- Confirm that monitoring captures error codes, session IDs, and correlation IDs.
- Confirm that support teams have troubleshooting and escalation procedures.
- Confirm that accessibility and responsive-layout tests pass.