How to test Stripe payments without fighting Checkout
By qtrl Team · Engineering
Checkout is the flow everyone wants covered. If sign-up breaks you lose new users. If payment breaks you lose money, and usually nobody finds out until support does. So the first end-to-end test many teams write opens the checkout page, types 4242 4242 4242 4242 into the card field, and clicks Pay.
That test is fighting Stripe, and Stripe's own automated testing guide says so plainly:
"Front-end interfaces, like Stripe Checkout or the Payment Element, have security measures in place that prevent automated testing, and Stripe APIs are rate limited."
Fraud protection that stops bots from testing stolen cards also stops your Playwright suite. Fighting that is a losing game. The better move is to split the payment flow into the parts you own and the parts Stripe owns, and test each where it's cheapest.
Five layers, five different tests
Most payment bugs we'd worry about live in the layers you own: the UI that shows a decline, the server code that creates the payment, and the webhook handler that decides whether the customer gets what they paid for. Those can be tested on every pull request without touching Stripe's frontend at all. The Stripe-hosted part gets a small number of real runs, on purpose.
Before you start: use a sandbox per purpose
Stripe now calls the old test mode the legacy test mode sandbox, and lets you create up to five general sandboxes next to it. Their guidance is to "use separate sandboxes for local development and continuous integration (CI)." Do that. A developer replaying webhooks locally shouldn't be able to fail a CI run, and CI shouldn't fill your local dashboard with test customers.
Keep the rate limits in mind too. A sandbox allows 25 requests per second across the account, a quarter of the live limit. A parallel suite where every worker creates customers and payments can hit that on its own, and a 429 in the middle of a checkout test looks just like a bug.
Layer 1: your checkout UI
The interesting UI behavior is what happens around the payment, not inside the card field. Does a decline show a message the customer can act on? Does the form stay editable so they can try another card? Is the Pay button disabled while confirmation is running, so a double click doesn't charge twice?
Stripe's suggestion for testing this is practical: confirm a payment with a decline card once by hand, log the error object that confirmPayment returns, and hard-code it in your tests. If you wrap Stripe.js calls in a small module of your own, mocking it in a component test is straightforward:
// checkout-form.test.tsx (Vitest + Testing Library)
vi.mock('@/lib/payments', () => ({
confirmPayment: vi.fn().mockResolvedValue({
// Copied from a real sandbox run with a decline test card
error: {
type: 'card_error',
code: 'card_declined',
decline_code: 'insufficient_funds',
message: 'Your card has insufficient funds.',
},
}),
}))
it('shows the decline reason and lets the customer try again', async () => {
render(<CheckoutForm amount={2000} />)
await user.click(screen.getByRole('button', { name: /pay/i }))
expect(await screen.findByText(/insufficient funds/i)).toBeVisible()
expect(screen.getByRole('button', { name: /pay/i })).toBeEnabled()
})Do the same for the error types your copy handles differently (expired card, incorrect CVC, a processing error), and for the success path: your confirmation page should render from the data your server stored, not from query parameters someone could edit.
Layer 2: your server calls to Stripe
Server-side code is where Stripe's test PaymentMethods are most useful. In a sandbox, pm_card_visa succeeds and the testing docs list a PaymentMethod or card number for most outcomes you'd want: generic declines, insufficient funds, incorrect CVC, and cards that require authentication. Stripe recommends using these PaymentMethods rather than raw card numbers in server code, even in a sandbox.
Running real sandbox calls on every pull request runs into the rate limits, so split it. A nightly job runs the server tests against a CI sandbox and saves the responses. Pull request runs use those saved responses as fixtures. When Stripe changes a response shape, the nightly job notices first.
You may also come across stripe-mock, Stripe's mock HTTP server. It's handy for checking that your requests are well formed, but it's stateless and its README is clear that it doesn't try to reproduce Stripe's behavior. It returns success where the real API would return an error, so don't use it to test error handling.
Layer 3: webhooks and fulfillment
This is the layer we'd test hardest, because it's where money and product state meet. A customer can pay successfully, close the tab before your success page loads, and still expect their order. The webhook is what makes that work, and it has to cope with events that arrive twice, late, or out of order.
For local development, the Stripe CLI forwards sandbox events to your machine and can trigger them on demand. Current versions require you to say which events to forward, with --events or with --all-snapshot for everything.
stripe listen \
--events checkout.session.completed,payment_intent.payment_failed \
--forward-to localhost:3000/api/webhooks/stripe
# In another terminal
stripe trigger checkout.session.completedstripe listen prints a whsec_ signing secret for your local handler, and it stays the same between restarts. In CI, you don't need the CLI at all. The Node SDK can sign a payload with a secret you control, so you can call your handler directly with events you design, including the awkward ones:
import Stripe from 'stripe'
import { POST } from '@/app/api/webhooks/stripe/route'
const stripe = new Stripe('sk_test_unused')
const secret = process.env.STRIPE_WEBHOOK_SECRET! // same value the handler reads
function signed(event: object) {
const payload = JSON.stringify(event)
const header = stripe.webhooks.generateTestHeaderString({ payload, secret })
return new Request('http://localhost/api/webhooks/stripe', {
method: 'POST',
headers: { 'stripe-signature': header },
body: payload,
})
}
it('fulfills an order once when the same event arrives twice', async () => {
const order = await createPendingOrder()
const event = checkoutCompletedEvent({ id: 'evt_dup_1', orderId: order.id })
await POST(signed(event))
await POST(signed(event))
expect(await countFulfillments(order.id)).toBe(1)
})createPendingOrder, checkoutCompletedEvent and countFulfillments stand in for your own helpers. The cases worth writing are the ones production will eventually send you:
- The same event twice. Fulfill once.
- A bad or missing signature. Reject it before touching the database.
- A
payment_intent.payment_failedafter the customer retried and succeeded. The order should stay paid. - An event for an object you don't know about, like a payment created from the Stripe dashboard. Log it and return 2xx, so Stripe doesn't keep retrying something you'll never handle.
Layer 4: subscriptions over time
Renewals, trials ending, failed renewals and dunning all happen weeks or months after sign-up. Stripe's test clocks (called simulations in the dashboard) let you create customers on a clock and move it forward, and Stripe fires the webhooks as if that time had passed.
They come with limits worth designing around: three customers per clock, three subscriptions per customer, and a clock only moves forward, at most two billing intervals per advance. Clocks delete themselves after 30 days. That makes them a fit for a nightly or weekly job with one clock per scenario (trial converts, renewal fails then recovers, plan change mid-cycle), not for a fast PR check.
Layer 5: Stripe's hosted UI and 3D Secure
Some things only show up in a real browser: your Payment Element configuration, the redirect back from Checkout, and the 3D Secure challenge. Stripe's test card 4000 0027 6000 3184 always asks for authentication, and in a sandbox the challenge is a mock page where you choose to complete or fail it.
Run these on a schedule or before a release, not on every PR, and keep them few. When you do automate one, expect nested iframes. Stripe doesn't document the iframe titles or field labels, so check them in DevTools rather than copying selectors from a tutorial:
// Selectors are illustrative. Confirm titles and labels in DevTools first.
const card = page.locator('iframe[title*="Secure payment input"]').first().contentFrame()
await card.getByLabel(/card number/i).fill('4000002760003184')
await card.getByLabel(/expiration/i).fill('12/34')
await card.getByLabel(/security code|cvc/i).fill('123')
await page.getByRole('button', { name: 'Pay' }).click()
// The 3DS challenge opens in its own nested iframe: complete or fail it thereIf these runs keep getting blocked, that's the security layer doing its job. A tester working through the flow with the test cards before a release is a perfectly good substitute, as long as the checks are written down and the results are recorded somewhere. Those runs are the kind of manual test case worth keeping in your test management next to the automated ones.
What runs where
Put together, a setup we'd be comfortable shipping payments on looks like this:
- Every pull request: UI tests with recorded Stripe.js results, server tests on recorded fixtures, and webhook handler tests with signed payloads. No calls to Stripe, fast and deterministic.
- Nightly: server tests against a CI sandbox that refresh the fixtures, plus the test clock scenarios.
- Before a release that touches billing: a short pass through the real checkout with a success card, a decline card and a 3D Secure card, automated or by hand.
- After deploy: watch for failed webhook deliveries in the Stripe dashboard. It's the cheapest production check you'll ever set up.
The browser test that types 4242 is still in there. It just stopped being the only thing standing between a refactor and a broken checkout.
qtrl keeps manual and automated test cases in one place, so the pre-release checkout pass lives next to your automated suite instead of in a forgotten doc. Write the steps once in plain language, keep test card numbers and sandbox URLs in per-environment variables, and record each run with its evidence and review state. Where a flow can be automated, an AI agent can run the case in a real browser and keep screenshots of every step. Start with your checkout test plan.
Have more questions about AI testing and QA? Check out our FAQ