본문으로 건너뛰기
cccskills
무료GitHub에 공개

stripe-subscription-billing-test-author

Builds test suites for Stripe recurring-billing flows: trial-to-paid conversion, proration on plan upgrade and downgrade, dunning on failed renewal, cancel and reactivation, and the full subscription webhook event matrix (invoice.payment_failed, customer.subscription.updated, customer.subscription.deleted, invoice.paid). Uses Stripe Billing test clocks (POST /v1/test_helpers/test_clocks) to time-travel through billing cycles without calendar delay. Distinct from stripe-test-cards-and-webhooks (one-time PaymentIntents) and payment-flow-test-author (idempotency + replay robustness). Does not cover single-event CLI replay or handler idempotency testing (see payment-flow-test-author for those). Use when authoring tests for subscription or recurring-billing integrations.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa스타 13(GitHub 13 + cccskills 0)
연동 도구Stripe

실행 점수 미검증

설치 방법 보기

포함된 파일(2)

  • SKILL.md13.6 KB
  • .tessl-plugin/plugin.json931 B

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

stripe-subscription-billing-test-author

Overview

Subscription billing is distinct from one-time payments. A customer's card is charged on a schedule, trials expire, plans change mid-cycle, and payments fail weeks after signup. Per docs.stripe.com/billing/testing, Stripe's sandbox is feature-complete for billing objects: subscriptions, invoices, trials, and retry schedules all work against test data.

The key tool for deterministic subscription testing is the Stripe Billing test clock, which lets you fast-forward a frozen simulation through days, weeks, or months without waiting. Per docs.stripe.com/api/test_clocks, a test clock is created at a frozen_time and advanced with POST /v1/test_helpers/test_clocks/{id}/advance, triggering all billing events that would have fired in the elapsed interval.

This skill walks through five recurring-billing scenarios end to end.

Lifecycle states to test

Per docs.stripe.com/billing/subscriptions/overview, subscriptions move through:

StateMeaning
trialingTrial active; no payment collected yet
activeGood standing; payment collected
past_dueLatest invoice unpaid; smart retries running
unpaidRetries exhausted; access decision pending
canceledTerminal; billing stopped
pausedTrial ended without payment method attached

Each transition fires one or more webhook events. Tests must assert both the subscription status and the correct event sequence.

Step 1 - Create a test clock

Per docs.stripe.com/api/test_clocks, create a test clock frozen at a known epoch before creating any billing objects:

const clock = await stripe.testHelpers.testClocks.create({
  frozen_time: Math.floor(new Date('2025-01-01T00:00:00Z').getTime() / 1000),
  name: 'billing-suite-run',
});

Attach the customer to the clock at creation time:

const customer = await stripe.customers.create({
  email: 'tester@example.com',
  test_clock: clock.id,
  payment_method: 'pm_card_visa',  // 4242 4242 4242 4242
  invoice_settings: { default_payment_method: 'pm_card_visa' },
});

Advance time with:

await stripe.testHelpers.testClocks.advance(clock.id, {
  advances_to: Math.floor(new Date('2025-01-08T00:00:00Z').getTime() / 1000),
});
// Poll until clock.status === 'ready' before asserting

Always poll GET /v1/test_helpers/test_clocks/{id} until status is ready before asserting subscription state; events are asynchronous.

Step 2 - Trial-to-paid conversion

Per docs.stripe.com/billing/testing, the recommended flow:

// Freeze clock at Jan 1
const sub = await stripe.subscriptions.create({
  customer: customer.id,
  items: [{ price: PRICE_ID }],
  trial_end: Math.floor(new Date('2025-01-08T00:00:00Z').getTime() / 1000),
});
expect(sub.status).toBe('trialing');

// Advance to Day 5 - trial_will_end fires 3 days before trial ends
await stripe.testHelpers.testClocks.advance(clock.id, {
  advances_to: toEpoch('2025-01-05'),
});
await waitForClockReady(clock.id);
// Assert: customer.subscription.trial_will_end webhook fired

// Advance past trial end (Day 8)
await stripe.testHelpers.testClocks.advance(clock.id, {
  advances_to: toEpoch('2025-01-09'),
});
await waitForClockReady(clock.id);

const updated = await stripe.subscriptions.retrieve(sub.id);
expect(updated.status).toBe('active');

Webhook events to assert per docs.stripe.com/billing/testing:

Clock positionEvent
Day 5customer.subscription.trial_will_end
Day 8invoice.created, invoice.finalized, invoice.paid
Day 8customer.subscription.updated (status: trialing -> active)

Step 3 - Proration on upgrade/downgrade

Per docs.stripe.com/billing/subscriptions/prorations, a mid-cycle plan change generates a credit for unused time on the old price and a charge for remaining time on the new price. Preview before applying:

const prorationDate = Math.floor(Date.now() / 1000);

// Preview the upcoming invoice to verify proration amounts
const preview = await stripe.invoices.createPreview({
  customer: customer.id,
  subscription: sub.id,
  subscription_details: {
    items: [{ id: sub.items.data[0].id, price: NEW_PRICE_ID }],
    proration_date: prorationDate,
  },
});

// Verify credit (negative) and debit (positive) line items exist
const credit = preview.lines.data.find(l => l.amount < 0);
const debit  = preview.lines.data.find(l => l.amount > 0);
expect(credit).toBeTruthy();
expect(debit).toBeTruthy();

// Apply at the same proration_date to lock the amounts
await stripe.subscriptions.update(sub.id, {
  items: [{ id: sub.items.data[0].id, price: NEW_PRICE_ID }],
  proration_date: prorationDate,
  proration_behavior: 'create_prorations',  // default
});

Per docs.stripe.com/billing/subscriptions/prorations, proration_behavior options are:

ValueEffect
create_prorationsCreates proration items; billed on next invoice (default)
always_invoiceCreates proration items AND immediately invoices
noneNo proration; full new price on next cycle

Downgrade test: pass a lower-priced plan as NEW_PRICE_ID and assert the credit line item is larger than the debit line item.

Step 4 - Dunning on failed renewal

Per docs.stripe.com/billing/testing, use test card 4000 0000 0000 0341 to trigger payment failure on an active subscription. Per docs.stripe.com/billing/revenue-recovery/smart-retries, Smart Retries can be configured for up to 8 attempts within a 2-month window; invoice.payment_failed fires on each failed attempt with attempt_count and next_payment_attempt fields.

// Attach a card that will decline on recurring collection
const failMethod = await stripe.paymentMethods.attach('pm_card_chargeDeclinedInsufficientFunds', {
  customer: customer.id,
});
await stripe.customers.update(customer.id, {
  invoice_settings: { default_payment_method: failMethod.id },
});

// Advance past the renewal date
await stripe.testHelpers.testClocks.advance(clock.id, {
  advances_to: toEpoch('2025-02-02'),  // One day past renewal
});
await waitForClockReady(clock.id);

const invoice = await getLatestInvoice(sub.id);
expect(invoice.status).toBe('open');

const sub2 = await stripe.subscriptions.retrieve(sub.id);
expect(sub2.status).toBe('past_due');
// Assert invoice.payment_failed was received with attempt_count >= 1

Webhook sequence on failed renewal:

EventKey field to assert
invoice.payment_failedattempt_count, next_payment_attempt
customer.subscription.updatedstatus: past_due

Test recovery: attach a valid payment method, then call stripe.invoices.pay(invoice.id) and assert invoice.paid fires and subscription returns to active.

Step 5 - Cancel and reactivation

// Cancel at period end (access persists until billing cycle closes)
await stripe.subscriptions.update(sub.id, { cancel_at_period_end: true });
const canceling = await stripe.subscriptions.retrieve(sub.id);
expect(canceling.cancel_at_period_end).toBe(true);

// Advance past period end
await stripe.testHelpers.testClocks.advance(clock.id, {
  advances_to: toEpoch('2025-02-02'),
});
await waitForClockReady(clock.id);

const canceled = await stripe.subscriptions.retrieve(sub.id);
expect(canceled.status).toBe('canceled');
// Assert: customer.subscription.deleted webhook fired

// Reactivation: create a new subscription (canceled is terminal)
const reactivated = await stripe.subscriptions.create({
  customer: customer.id,
  items: [{ price: PRICE_ID }],
});
expect(reactivated.status).toBe('active');

Per docs.stripe.com/billing/subscriptions/overview, canceled is a terminal state; reactivation means creating a fresh subscription, not updating the canceled one.

Step 6 - Webhook event matrix

Per docs.stripe.com/billing/testing, the full set of events your handler must process:

EventTriggerRequired handler action
customer.subscription.createdNew subscriptionRecord subscription ID + status
customer.subscription.trial_will_end3 days before trial endNotify customer
customer.subscription.updatedAny status or plan changeSync local subscription record
customer.subscription.deletedCancellation takes effectRevoke access
invoice.createdInvoice generated at renewalFinalize within 72 hours
invoice.finalizedInvoice ready for collectionLog for audit
invoice.paidPayment succeededProvision or extend access
invoice.payment_failedPayment attempt failedNotify customer; track attempt_count
invoice.payment_action_required3DS required on renewalPrompt re-authentication

Trigger these in CI using the Stripe CLI:

stripe trigger invoice.payment_failed
stripe trigger customer.subscription.updated

Per docs.stripe.com/stripe-cli, forward webhook events to a local handler during development:

stripe listen --forward-to http://localhost:3000/webhooks/stripe

Running

npm test -- --testPathPattern=billing

For integration tests that drive test clocks:

STRIPE_TEST_KEY=sk_test_... npm test -- --testPathPattern=billing/integration

CI integration

jobs:
  billing-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v4
      - run: npm ci && npm test -- --testPathPattern=billing
        env:
          STRIPE_TEST_KEY: ${{ secrets.STRIPE_TEST_KEY }}
          STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }}

Test-clock tests do not require stripe listen because they drive the Stripe API directly without local webhook forwarding. Signature verification tests do need STRIPE_WEBHOOK_SECRET.

Anti-patterns

Anti-patternWhy it failsFix
setTimeout to wait for trial endFlaky and slow in CIUse test clock + waitForClockReady
Asserting subscription state before clock is readyRace condition; events not yet firedPoll GET /v1/test_helpers/test_clocks/{id}
Reusing a test clock customer across test casesShared state leaks between scenariosCreate a fresh clock + customer per scenario
Canceling and immediately reusing as activecanceled is terminalCreate a new subscription for reactivation
Skipping invoice.paid handlerAccess provisioned on subscription create, not paymentProvision only after invoice.paid
Omitting proration_date from preview AND update callsTiming skew makes amounts disagreeUse the same epoch timestamp for both
Testing only invoice.payment_failed onceSmart Retries fires multiple times with growing attempt_countTest at least two retry cycles

Limitations

  • Test clocks only work in sandbox (test mode); they are not available in live mode.
  • Per docs.stripe.com/api/test_clocks, a test clock cannot be advanced backward; frozen time is monotonically forward-only.
  • Smart Retry timing in test mode compresses retry intervals; exact retry schedule differs from production per docs.stripe.com/billing/revenue-recovery/smart-retries.
  • Stripe CLI trigger sends synthetic events; test-clock-driven tests produce real invoice objects and are preferred for billing accuracy.

References

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Builds a CI gate that fails the build on **new** WCAG / a11y violations introduced by a PR while grandfathering pre-existing violations on a per-rule / per-page baseline. Aggregates verdicts from axe-core / pa11y / Lighthouse a11y / WAVE / IBM Equal Access scans. Use when a project has accumulated a11y debt and a strict "zero violations" gate would block every PR - the ratchet pattern lets the team ship while preventing regressions.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Workflow skill that builds an A/B-test validity checklist from an experiment proposal, walking the canonical design-correctness gates - pre-registered OEC/power/guardrails, randomization unit + SRM check, assignment integrity, telemetry, peeking discipline, novelty/primacy, post-experiment SRM re-check - into a per-experiment checklist + sign-off form. Use when launching, auditing, or governing an experiment. For pitfall mechanics (guardrails, peeking) see experiment-results-interpreter's references; to read an already-valid result use experiment-results-interpreter; for per-SDK harness tests use experiment-sdk-testing - this gates DESIGN, not SDK code.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

The single install-flow skill: the reference contract for the PWA install flow (installability gate fields, `beforeinstallprompt` handshake, per-platform paths - Android WebAPK / iOS Share menu / Firefox no-op - and the `display-mode` post-install signal, in references/install-flow-reference.md) plus the build-an-X workflow that emits the Add-to-Home-Screen suite. Walks the four-stage timeline, emitting one test per gate cell per [web.dev/articles/install-criteria][install-criteria], the deferred-prompt → `prompt()` → `userChoice` chain per [web.dev/articles/customize-install][customize-install], the iOS Safari manual-metadata branch (`apple-touch-icon`) per [web.dev/learn/pwa/installation][learn-pwa], and the post-install `(display-mode: standalone)` MQ assertion. Output: a Playwright spec with per-stage cells plus a coverage matrix. Use when a PWA's manifest, icons, or install handler change, when install conversion drops at an unknown stage, or when triaging a flaky install assertion.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Build-an-X workflow that uses an LLM to map existing tests to spec sections - given a spec doc + the test suite, the LLM identifies which tests cover which sections, surfaces uncovered sections (gap), and recommends specific tests to add. Output is a coverage matrix per spec ID. Scope is mapping tests that already exist and naming the gaps, not authoring tests for new acceptance criteria. Use when a spec doc and a test suite both exist but nobody can say which requirements are actually covered - before a release sign-off, an audit, or a decision about where to spend the next round of test effort.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Generates tests from natural-language specs (acceptance criteria, user stories, requirements) using an LLM, with confidence scoring per test case (LLM self-assessment plus heuristics: assertion quality, naming, completeness), batching uncertain cases for human review, and integration with the team's existing test framework. Use when the user asks to generate unit tests from acceptance criteria, convert user stories to test cases, automate test creation from requirements, or augment a spec-driven test suite with AI-generated stubs that are then curated before merge.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Configures Allure Report (test-runner adapter install, `allure-results` directory wiring, `categories.json` for failure classification, `history-trend.json` retention via the copy-history-between-runs pattern), runs the Allure CLI to convert `allure-results` to a static HTML site, and uploads the report as a CI artifact. Use when the team needs richer test reporting than JUnit XML - step-level attachments, per-test history, retry tracking, and severity / epic / feature labeling across framework-agnostic adapters (pytest, Jest, JUnit, TestNG, NUnit, Mocha). As a rich static HTML report generator, it is the open-source alternative to the sunset ExtentReports (JVM/.NET per-test HTML narrative); for hosted cross-run flakiness analytics rather than a static per-run report use currents-integration.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

testland의 스킬 모두 보기

이 스킬의 문제 신고