|
| 1 | +import test from "node:test"; |
| 2 | +import assert from "node:assert/strict"; |
| 3 | +import { createApp } from "../app.js"; |
| 4 | +import { setStripeClientForTests } from "../services/paymentService.js"; |
| 5 | + |
| 6 | +async function withServer(callback) { |
| 7 | + const app = createApp(); |
| 8 | + const server = app.listen(0); |
| 9 | + |
| 10 | + await new Promise((resolve, reject) => { |
| 11 | + server.once("listening", resolve); |
| 12 | + server.once("error", reject); |
| 13 | + }); |
| 14 | + |
| 15 | + try { |
| 16 | + const { port } = server.address(); |
| 17 | + await callback(`http://127.0.0.1:${port}`); |
| 18 | + } finally { |
| 19 | + await new Promise((resolve, reject) => { |
| 20 | + server.close((error) => (error ? reject(error) : resolve())); |
| 21 | + }); |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +test("POST /api/payments returns Stripe client secret", async () => { |
| 26 | + setStripeClientForTests({ |
| 27 | + paymentIntents: { |
| 28 | + async create() { |
| 29 | + return { |
| 30 | + id: "pi_route_123", |
| 31 | + client_secret: "pi_route_123_secret" |
| 32 | + }; |
| 33 | + } |
| 34 | + } |
| 35 | + }); |
| 36 | + |
| 37 | + await withServer(async (baseUrl) => { |
| 38 | + const response = await fetch(`${baseUrl}/api/payments`, { |
| 39 | + method: "POST", |
| 40 | + headers: { "content-type": "application/json" }, |
| 41 | + body: JSON.stringify({ amount: 1999 }) |
| 42 | + }); |
| 43 | + const payload = await response.json(); |
| 44 | + |
| 45 | + assert.equal(response.status, 201); |
| 46 | + assert.equal(payload.data.paymentId, "pi_route_123"); |
| 47 | + assert.equal(payload.data.clientSecret, "pi_route_123_secret"); |
| 48 | + }); |
| 49 | +}); |
| 50 | + |
| 51 | +test("POST /api/payments returns 400 for invalid amount", async () => { |
| 52 | + await withServer(async (baseUrl) => { |
| 53 | + const response = await fetch(`${baseUrl}/api/payments`, { |
| 54 | + method: "POST", |
| 55 | + headers: { "content-type": "application/json" }, |
| 56 | + body: JSON.stringify({ amount: -1 }) |
| 57 | + }); |
| 58 | + const payload = await response.json(); |
| 59 | + |
| 60 | + assert.equal(response.status, 400); |
| 61 | + assert.equal(payload.error, "amount must be a positive integer in the smallest currency unit"); |
| 62 | + }); |
| 63 | +}); |
0 commit comments