Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@
"editor.codeActionsOnSave": {
"quickfix.biome": "explicit",
},
"editor.formatOnSave": true
}
"editor.formatOnSave": true,
"cSpell.words": [
"Braintree"
]
}
20 changes: 20 additions & 0 deletions plugins/braintree-payment/jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/** @type {import('jest').Config} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.spec.ts', '**/*.spec.ts'],
transform: {
'^.+\\.(ts|tsx)$': [
'ts-jest',
{ tsconfig: '<rootDir>/tsconfig.spec.json', diagnostics: false, isolatedModules: true }
],
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
verbose: false,
collectCoverage: false,
// Ignore compiled medusa build output
testPathIgnorePatterns: ['/node_modules/', '/.medusa/'],
};


8 changes: 6 additions & 2 deletions plugins/braintree-payment/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@lambdacurry/medusa-payment-braintree",
"version": "0.0.8",
"version": "0.0.9",
"description": "Braintree plugin for Medusa",
"author": "Lambda Curry (https://lambdacurry.dev)",
"license": "MIT",
Expand Down Expand Up @@ -47,11 +47,15 @@
"@medusajs/ui": "^4.0.3",
"@swc/core": "1.5.7",
"@types/braintree": "^3.3.14",
"@types/jest": "^29.5.12",
"@types/jsonwebtoken": "^9.0.10",
"jsonwebtoken": "^9.0.2"
"jest": "^29.7.0",
"jsonwebtoken": "^9.0.2",
"ts-jest": "^29.2.5"
},
Comment on lines +50 to 55
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Confirm TypeScript is available for ts-jest to work.
ts-jest requires TypeScript in the dependency graph. I don’t see "typescript" declared in this package; if it’s only at the repo root, that’s fine for a monorepo, but worth verifying to avoid runtime transform errors.

Run this script to confirm TypeScript is present somewhere in the workspace and check jest/ts-jest versions:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Searching for TypeScript in any package.json..."
rg -nP -C2 --no-ignore-vcs --glob 'package.json' '\b"typescript"\s*:\s*"' || true

echo
echo "Checking plugin test tooling versions from plugins/braintree-payment/package.json..."
if command -v jq >/dev/null 2>&1; then
  jq '{ jest: .devDependencies.jest, tsjest: .devDependencies["ts-jest"], typescript: .devDependencies.typescript }' plugins/braintree-payment/package.json
else
  sed -n '1,120p' plugins/braintree-payment/package.json | rg -n '("jest"|"ts-jest"|"typescript")\s*:\s*"[^"]+"'
fi

echo
echo "Verifying jest config presence..."
rg -n -C2 --type-add 'cjs:*.cjs' --type cjs 'module\.exports|export' plugins/braintree-payment/jest.config.cjs || fd -a jest.config.cjs plugins/braintree-payment || true

Length of output: 943


Ensure TypeScript is declared for ts-jest
We’re using the ts-jest preset in plugins/braintree-payment/jest.config.cjs, but I don’t see typescript in this package’s dependencies. ts-jest requires TypeScript in the dependency graph to compile tests.

Please update:

  • File: plugins/braintree-payment/package.json
    • Under devDependencies, add
    "typescript": "<your repo’s TS version>"
    or confirm that the root workspace’s typescript is installed and will be hoisted into this package to avoid runtime transform failures.
🤖 Prompt for AI Agents
In plugins/braintree-payment/package.json around lines 50-55, ts-jest is used
but TypeScript is not declared; add "typescript" to this package's
devDependencies using the repository's TypeScript version (or confirm the root
workspace's typescript will be hoisted into this package), then run install to
ensure ts-jest can resolve the compiler; update package.json devDependencies
accordingly and commit the change.

"scripts": {
"build": "npx medusa plugin:build",
"test": "jest --config jest.config.cjs --runInBand",
"plugin:dev": "npx medusa plugin:develop",
"prepublishOnly": "npx medusa plugin:build"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,279 @@
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
import BraintreeProviderService from '../../services/braintree-provider';
import { BraintreeConstructorArgs, BraintreePaymentSessionData } from '../braintree-base';

const buildService = () => {
const logger = { info: jest.fn(), warn: jest.fn(), error: jest.fn() } as any;
const cache = { get: jest.fn(), set: jest.fn() } as any;

const container: BraintreeConstructorArgs = {
logger,
cache,
};

const options = {
environment: 'sandbox' as const,
merchantId: 'merchant',
publicKey: 'public',
privateKey: 'private',
enable3DSecure: false,
savePaymentMethod: false,
webhookSecret: 'whsec',
autoCapture: true,
} as any; // satisfy BraintreeOptions without bringing full type deps

const service = new BraintreeProviderService(container, options);

// Replace gateway with a mock implementation
const gateway = {
clientToken: { generate: jest.fn() },
transaction: {
sale: jest.fn(),
find: jest.fn(),
submitForSettlement: jest.fn(),
void: jest.fn(),
refund: jest.fn(),
},
paymentMethod: { create: jest.fn() },
customer: { find: jest.fn(), create: jest.fn(), update: jest.fn(), delete: jest.fn() },
webhookNotification: { parse: jest.fn() },
} as any;

(service as any).gateway = gateway;

return { service, gateway, logger, cache };
};

describe('BraintreeProviderService core behaviors', () => {
beforeEach(() => {
jest.resetAllMocks();
});

afterEach(() => {
jest.useRealTimers();
});

it('returns cached client token when available', async () => {
const { service, gateway, cache } = buildService();
cache.get.mockResolvedValueOnce('cached-token');

const token = await (service as any).getValidClientToken('cust_1');

expect(token).toBe('cached-token');
expect(gateway.clientToken.generate).not.toHaveBeenCalled();
});

it('generates and caches client token when missing, with correct TTL', async () => {
const { service, gateway, cache } = buildService();
jest.useFakeTimers();
jest.setSystemTime(new Date('2020-01-01T00:00:00Z'));

cache.get.mockResolvedValueOnce(null);
gateway.clientToken.generate.mockResolvedValueOnce({ clientToken: 'new-token' });

const token = await (service as any).getValidClientToken('cust_2');

expect(token).toBe('new-token');
expect(cache.set).toHaveBeenCalled();
const setArgs = cache.set.mock.calls[0];
// [key, value, ttlSeconds]
expect(setArgs[1]).toBe('new-token');
// 24h - 1s
expect(setArgs[2]).toBe(24 * 3600 - 1);
});

it('authorizePayment creates a sale with decimal string amount (2dp) and returns captured when autoCapture=true', async () => {
const { service, gateway } = buildService();

const input = {
data: {
clientToken: 'ct',
amount: 10, // standard unit -> "10.00"
currency_code: 'USD',
paymentMethodNonce: 'fake-nonce',
},
context: {
idempotency_key: 'idem_1',
customer: { id: 'cust', email: '[email protected]' },
},
} as any;

gateway.transaction.sale.mockResolvedValueOnce({ success: true, transaction: { id: 't1' } });
gateway.transaction.find.mockResolvedValue({ id: 't1', status: 'authorized', amount: '10.00' });

const result = await service.authorizePayment(input);

expect(gateway.transaction.sale).toHaveBeenCalled();
const saleArgs = gateway.transaction.sale.mock.calls[0][0];
expect(saleArgs.amount).toBe('10.00');
expect(result.status).toBe('captured');
});

it('capturePayment submits for settlement when status is authorized', async () => {
const { service, gateway } = buildService();

const input = {
data: {
clientToken: 'ct',
amount: 1000,
currency_code: 'USD',
braintreeTransaction: { id: 't1' },
},
} as any;

gateway.transaction.find
.mockResolvedValueOnce({ id: 't1', status: 'authorized', amount: '10.00' }) // pre-check
.mockResolvedValueOnce({ id: 't1', status: 'submitted_for_settlement', amount: '10.00' }); // retrieve after submit
gateway.transaction.submitForSettlement.mockResolvedValueOnce({ success: true });

const result = await service.capturePayment(input);

expect(gateway.transaction.submitForSettlement).toHaveBeenCalledWith('t1', '10.00');

const data = result.data as unknown as BraintreePaymentSessionData;
expect(data?.braintreeTransaction?.id).toBe('t1');
});

it('refundPayment voids when transaction is authorized', async () => {
const { service, gateway } = buildService();

const input = {
amount: 5, // standard unit, will be converted internally
data: {
clientToken: 'ct',
amount: 1000,
currency_code: 'USD',
braintreeTransaction: { id: 't1' },
},
} as any;

gateway.transaction.find.mockResolvedValueOnce({ id: 't1', status: 'authorized' });
gateway.transaction.void.mockResolvedValueOnce({ success: true });
gateway.transaction.find.mockResolvedValueOnce({ id: 't1', status: 'voided' });

const result = await service.refundPayment(input);

expect(gateway.transaction.void).toHaveBeenCalledWith('t1');
expect((result.data as any)?.braintreeRefund?.success).toBe(true);
});

it('refundPayment voids when transaction is submitted_for_settlement', async () => {
const { service, gateway } = buildService();

const input = {
amount: 10, // standard unit
data: {
clientToken: 'ct',
amount: 1000,
currency_code: 'USD',
braintreeTransaction: { id: 't1' },
},
} as any;

gateway.transaction.find.mockResolvedValueOnce({ id: 't1', status: 'submitted_for_settlement' });
gateway.transaction.void.mockResolvedValueOnce({ success: true });
gateway.transaction.find.mockResolvedValueOnce({ id: 't1', status: 'voided' });

const result = await service.refundPayment(input);

expect(gateway.transaction.void).toHaveBeenCalledWith('t1');
expect((result.data as any)?.braintreeRefund?.success).toBe(true);
});

it('refundPayment refunds with 2dp when transaction is settling', async () => {
const { service, gateway } = buildService();

const input = {
amount: 7.5, // -> "7.50"
data: {
clientToken: 'ct',
amount: 1000,
currency_code: 'USD',
braintreeTransaction: { id: 't2' },
},
} as any;

gateway.transaction.find
.mockResolvedValueOnce({ id: 't2', status: 'settling' })
.mockResolvedValueOnce({ id: 't2', status: 'settling' });
gateway.transaction.refund.mockResolvedValueOnce({ transaction: { id: 'r2' } });

const result = await service.refundPayment(input);

expect(gateway.transaction.refund).toHaveBeenCalledWith('t2', '7.50');
expect((result.data as any)?.braintreeRefund?.id).toBe('r2');
});

it('refundPayment throws for non-refundable statuses', async () => {
const { service, gateway } = buildService();

const input = {
amount: 5,
data: {
clientToken: 'ct',
amount: 1000,
currency_code: 'USD',
braintreeTransaction: { id: 't3' },
},
} as any;

gateway.transaction.find.mockResolvedValueOnce({ id: 't3', status: 'failed' });

await expect(service.refundPayment(input)).rejects.toThrow();
expect(gateway.transaction.void).not.toHaveBeenCalled();
expect(gateway.transaction.refund).not.toHaveBeenCalled();
});

// NOTE: Import/refund simulation moved to the dedicated import provider tests

it('refundPayment refunds with 2dp decimal string when transaction is settled', async () => {
const { service, gateway } = buildService();

const input = {
amount: 5.001, // -> "5.00"
data: {
clientToken: 'ct',
amount: 1000,
currency_code: 'USD',
braintreeTransaction: { id: 't2' },
},
} as any;

gateway.transaction.find
.mockResolvedValueOnce({ id: 't2', status: 'settled' }) // retrieveTransaction
.mockResolvedValueOnce({ id: 't2', status: 'settled' }); // updated after refund
gateway.transaction.refund.mockResolvedValueOnce({ transaction: { id: 'r1' } });

const result = await service.refundPayment(input);

expect(gateway.transaction.refund).toHaveBeenCalledWith('t2', '5.00');
expect((result.data as any)?.braintreeRefund?.id).toBe('r1');
});

it('getPaymentStatus maps provider status correctly', async () => {
const { service, gateway } = buildService();
const input = { data: { braintreeTransaction: { id: 't3' } } } as any;
gateway.transaction.find.mockResolvedValueOnce({ id: 't3', status: 'failed' });

const result = await service.getPaymentStatus(input);
expect(result.status).toBe('error');
});

it('getWebhookActionAndData returns successful for transaction_settled', async () => {
const { service, gateway } = buildService();
const payloadStr = 'bt_signature=s&bt_payload=p';
gateway.webhookNotification.parse.mockResolvedValueOnce({
kind: 'transaction_settled',
transaction: { id: 't4' },
});
gateway.transaction.find.mockResolvedValueOnce({
id: 't4',
amount: '12.34',
customFields: { medusa_payment_session_id: 'sess_123' },
});

const result = await service.getWebhookActionAndData({ data: payloadStr } as any);
expect(result.action).toBe('captured');
expect((result as any).data.session_id).toBe('sess_123');
});
});
Loading