-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbilling.subscriptions.component.unit.tests.js
More file actions
1483 lines (1243 loc) · 55.5 KB
/
billing.subscriptions.component.unit.tests.js
File metadata and controls
1483 lines (1243 loc) · 55.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mount, flushPromises } from '@vue/test-utils';
import { createPinia, setActivePinia } from 'pinia';
import { createVuetify } from 'vuetify';
// ─── Prevent real HTTP calls ────────────────────────────────────────────────
vi.mock('../../../lib/services/axios', () => ({
default: { get: vi.fn(), post: vi.fn() },
}));
vi.mock('../../../lib/helpers/analytics', () => ({
capture: vi.fn(),
}));
// ─── Mutable auth store state (hoisted so vi.mock factory can close over it) ─
const authState = vi.hoisted(() => ({
isLoggedIn: true,
user: null,
serverConfig: null,
}));
vi.mock('../../auth/stores/auth.store', () => ({
useAuthStore: () => authState,
}));
// ─── Decouple from tenant-specific plan IDs ──────────────────────────────────
vi.mock('../lib/billing.resolveStaticContent.js', () => ({
resolveStaticContent: () => ({
plans: [{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }],
packs: [],
}),
}));
// ─── Imports (after mocks) ───────────────────────────────────────────────────
import { useBillingStore } from '../stores/billing.store';
import BillingSubscriptionsComponent from '../components/billing.subscriptions.component.vue';
// ─── Constants ───────────────────────────────────────────────────────────────
const mockConfig = {
api: {
protocol: 'http',
host: 'localhost',
port: '3000',
base: 'api',
endPoints: { billing: 'billing' },
},
vuetify: { theme: { rounded: '', flat: true, maxWidth: '1200px' } },
};
const mockUsageMeterNormal = {
plan: 'starter',
planVersion: 1,
weekKey: '2025-W17',
// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Qwik rule does not apply in a Vue/Vitest context
weekResetAt: new Date(Date.now() + 86400000).toISOString(),
meterUsed: 120,
meterQuota: 500,
meterBreakdown: { scrap: 80, autofix: 40 },
extrasRemaining: 50,
packsAvailable: [
{ packId: 'pack_500', label: '500 units', priceUsd: 9, meterUnits: 500 },
{ packId: 'pack_1000', label: '1000 units', priceUsd: 16, meterUnits: 1000 },
],
};
const mockExtrasBalance = {
balance: 50,
packsAvailable: mockUsageMeterNormal.packsAvailable,
};
// ─── Helpers ─────────────────────────────────────────────────────────────────
const vuetify = createVuetify();
const componentStubs = {
RouterLink: true,
BillingPlanBadgeComponent: true,
BillingExtrasCheckoutModalComponent: {
name: 'BillingExtrasCheckoutModalComponent',
props: ['modelValue', 'packs'],
emits: ['update:modelValue'],
template: '<div class="extras-modal-stub" :data-open="modelValue"><slot /></div>',
},
};
/**
* @desc Mount BillingSubscriptionsComponent with Vuetify + Pinia.
* @param {Object} [opts]
* @returns {import('@vue/test-utils').VueWrapper}
*/
function mountSubscriptions({
serverConfig = null,
isLoggedIn = true,
routeQuery = {},
router = { replace: vi.fn(), push: vi.fn() },
} = {}) {
authState.serverConfig = serverConfig;
authState.isLoggedIn = isLoggedIn;
return mount(BillingSubscriptionsComponent, {
global: {
plugins: [vuetify],
mocks: {
config: mockConfig,
$route: { path: '/users', query: routeQuery },
$router: router,
},
stubs: componentStubs,
},
});
}
/**
* @desc Seed billingStore with meter usage data and stub the fetch actions.
* @param {Object} store
* @param {Object} [usageMeter]
* @param {Object} [extrasBalance]
*/
function seedMeterStore(store, usageMeter = mockUsageMeterNormal, extrasBalance = mockExtrasBalance) {
store.usageMeter = usageMeter;
store.extrasBalance = extrasBalance;
vi.spyOn(store, 'fetchUsageMeter').mockResolvedValue(usageMeter);
vi.spyOn(store, 'fetchExtrasBalance').mockResolvedValue(extrasBalance);
vi.spyOn(store, 'fetchExtrasLedger').mockResolvedValue({ entries: [], total: 0, page: 1, limit: 20 });
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
vi.spyOn(store, 'fetchPlans').mockResolvedValue([]);
}
// ─── Suite 1: Meter mode rendering ───────────────────────────────────────────
describe('BillingSubscriptionsComponent — meter mode (meterMode: true)', () => {
let wrapper;
beforeEach(() => {
setActivePinia(createPinia());
vi.clearAllMocks();
const store = useBillingStore();
seedMeterStore(store);
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
vi.useRealTimers();
});
it('renders meter progress widget when meterMode is true', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
expect(wrapper.find('.billing-meter-progress').exists()).toBe(true);
});
it('renders breakdown chart when meterMode is true', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
expect(wrapper.find('.billing-meter-breakdown-chart').exists()).toBe(true);
});
it('renders meter usage values against combinedPool denominator', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
// combinedPool = meterQuota(500) + meterExtras(50) + meterUsed(120) = 670
// used(120) / combinedPool(670) = ~18%
expect(wrapper.text()).toContain('18%');
});
it('renders "Buy compute extras" CTA in meter mode (T6 redesign: /pricing#units redirect)', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
const buyBtns = wrapper.findAllComponents({ name: 'v-btn' }).filter((b) => b.text().includes('Buy compute extras'));
expect(buyBtns.length).toBeGreaterThan(0);
});
it('"Buy compute extras" CTA navigates to /pricing#units (not opens modal) — T6 redesign', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
const buyBtn = wrapper.findAllComponents({ name: 'v-btn' }).find((b) => b.text().includes('Buy compute extras'));
expect(buyBtn).toBeDefined();
// Must have `to="/pricing#units"` prop — never opens the inline checkout modal
const toProp = buyBtn?.props('to') ?? buyBtn?.attributes('to');
expect(String(toProp)).toContain('/pricing');
expect(String(toProp)).toContain('#units');
// Dialog must remain closed — this is not a modal trigger
expect(wrapper.vm.extrasCheckoutDialog).toBe(false);
});
it('does NOT render BillingUsageBarComponent in meter mode (T6: single bar only)', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
// T6 drops BillingUsageBarComponent — only BillingMeterProgressComponent remains
const usageBars = wrapper.findAllComponents({ name: 'BillingUsageBarComponent' });
expect(usageBars.length).toBe(0);
});
it('fetches extras ledger when meterMode is true', async () => {
const store = useBillingStore();
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
expect(store.fetchExtrasLedger).toHaveBeenCalledWith({ page: 1, limit: 20 });
});
it('does not fetch extras ledger when meterMode is false', async () => {
const store = useBillingStore();
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(store.fetchExtrasLedger).not.toHaveBeenCalled();
});
});
// ─── Suite 2: Legacy regression ──────────────────────────────────────────────
describe('BillingSubscriptionsComponent — legacy mode (meterMode: false)', () => {
let wrapper;
beforeEach(() => {
setActivePinia(createPinia());
vi.clearAllMocks();
const store = useBillingStore();
seedMeterStore(store);
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
});
it('does NOT render .billing-meter-progress in legacy mode', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.find('.billing-meter-progress').exists()).toBe(false);
});
it('does NOT render .billing-usage-bar--meter in legacy mode', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.find('.billing-usage-bar--meter').exists()).toBe(false);
});
it('does NOT render meter section labels in legacy mode', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).not.toContain('Weekly meter');
expect(wrapper.text()).not.toContain('Extra units');
});
it('renders Current Plan card in legacy mode', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).toContain('Current Plan');
});
});
// ─── Suite 3: Manage subscription / portal ──────────────────────────────────
describe('BillingSubscriptionsComponent — Manage Subscription', () => {
let wrapper;
let store;
beforeEach(() => {
setActivePinia(createPinia());
vi.clearAllMocks();
store = useBillingStore();
seedMeterStore(store);
store.subscription = { status: 'active', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
vi.spyOn(store, 'openPortal').mockResolvedValue('https://billing.stripe.com/session/test');
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
});
it('renders Manage Subscription button when subscription is active', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).toContain('Manage Subscription');
});
it('manageSubscription delegates to billingStore.openPortal', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
await wrapper.vm.manageSubscription();
expect(store.openPortal).toHaveBeenCalled();
});
it('manageSubscription calls window.open with the URL from openPortal', async () => {
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
await wrapper.vm.manageSubscription();
await flushPromises();
expect(openSpy).toHaveBeenCalledWith(
'https://billing.stripe.com/session/test',
'_blank',
'noopener,noreferrer',
);
openSpy.mockRestore();
});
it('does NOT render inline portal error alert when openPortal rejects (centralized snackbar handles it)', async () => {
store.openPortal.mockRejectedValueOnce(new Error('Portal failed'));
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
await wrapper.vm.manageSubscription();
await flushPromises();
// Error is surfaced via centralized snackbar — no inline alert in this component
expect(wrapper.text()).not.toContain('Unable to open the billing portal');
});
});
// ─── Suite 4: Status chips / paid plan CTA ─────────────────────────────────
describe('BillingSubscriptionsComponent — status and paid plan CTAs', () => {
let wrapper;
let store;
beforeEach(() => {
setActivePinia(createPinia());
vi.clearAllMocks();
store = useBillingStore();
seedMeterStore(store);
vi.spyOn(store, 'openPortal').mockResolvedValue(undefined);
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
});
it.each([
['active', 'success'],
['past_due', 'warning'],
['canceled', 'error'],
['incomplete', 'error'],
['incomplete_expired', 'error'],
['trialing', 'success'],
['paused', 'warning'],
['unpaid', 'error'],
])('renders %s subscription status with %s chip color', async (status, color) => {
store.subscription = { status, plan: 'starter', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
// i18n-translated statuses use their key label; others fall back to raw replacement
const i18nLabels = { paused: 'Paused', unpaid: 'Unpaid' };
const expectedLabel = i18nLabels[status] ?? status.replace(/_/g, ' ');
const chip = wrapper.findComponent({ name: 'v-chip' });
expect(chip.exists()).toBe(true);
expect(chip.props('color')).toBe(color);
expect(chip.text()).toContain(expectedLabel);
});
it('shows Update payment method action for past_due status', async () => {
store.subscription = { status: 'past_due', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).toContain('Update payment method');
});
it('shows Reactivate action for canceled status', async () => {
store.subscription = { status: 'canceled', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).toContain('Reactivate');
});
it('shows Complete payment action for incomplete_expired status with error color', async () => {
store.subscription = { status: 'incomplete_expired', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).toContain('Complete payment');
});
it('shows Reactivate action for paused status with warning color', async () => {
store.subscription = { status: 'paused', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).toContain('Reactivate');
});
it('shows Update payment method action for unpaid status with error color', async () => {
store.subscription = { status: 'unpaid', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).toContain('Update payment method');
});
it('labels the paid plan upgrade CTA as Change Plan when a higher plan exists', async () => {
store.subscription = { status: 'active', plan: 'p2', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).toContain('Change Plan');
expect(wrapper.text()).not.toContain('Upgrade');
});
it('hides the paid plan upgrade CTA on the highest plan', async () => {
store.subscription = { status: 'active', plan: 'pro', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.text()).not.toContain('Change Plan');
});
it('status chip for paused shows inlined English label "Paused"', async () => {
store.subscription = { status: 'paused', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
const wrapperPaused = mount(BillingSubscriptionsComponent, {
global: {
plugins: [vuetify],
mocks: {
config: mockConfig,
$route: { path: '/users', query: {} },
$router: { replace: vi.fn(), push: vi.fn() },
},
stubs: componentStubs,
},
});
await flushPromises();
const chip = wrapperPaused.findComponent({ name: 'v-chip' });
expect(chip.exists()).toBe(true);
expect(chip.text()).toContain('Paused');
wrapperPaused.unmount();
});
it('paid plan card has billing-subscriptions__plan-card--paid CSS class (primary accent border)', async () => {
store.subscription = { status: 'active', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
// The paid plan card carries the BEM modifier class used by the primary left-border accent rule
expect(wrapper.find('.billing-subscriptions__plan-card--paid').exists()).toBe(true);
expect(wrapper.find('.billing-subscriptions__plan-card--free').exists()).toBe(false);
});
it('free plan card has billing-subscriptions__plan-card--free CSS class (no accent border)', async () => {
store.subscription = null;
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
expect(wrapper.find('.billing-subscriptions__plan-card--free').exists()).toBe(true);
expect(wrapper.find('.billing-subscriptions__plan-card--paid').exists()).toBe(false);
});
});
// ─── Suite 5: Stripe success query handling ────────────────────────────────
describe('BillingSubscriptionsComponent — checkout success query flow', () => {
let wrapper;
let store;
beforeEach(() => {
setActivePinia(createPinia());
vi.useFakeTimers();
vi.clearAllMocks();
sessionStorage.clear();
store = useBillingStore();
seedMeterStore(store);
store.subscription = { status: 'active', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
vi.useRealTimers();
sessionStorage.clear();
});
it('shows processing state and cleans the URL query on ?success=true (P1-2 polling flow)', async () => {
const router = { replace: vi.fn(), push: vi.fn() };
// fetchSubscription never activates subscription → stays in processing/polling
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { tab: 'subscriptions', success: 'true' },
router,
});
await flushPromises();
// Polling is active — checkoutProcessing shown
expect(wrapper.vm.checkoutProcessing).toBe(true);
// URL cleanup fires after 100ms
vi.advanceTimersByTime(100);
expect(router.replace).toHaveBeenCalledWith({
query: { tab: 'subscriptions', success: undefined, type: undefined, packPurchased: undefined },
});
});
it('shows extras success copy when Stripe returns type=extras', async () => {
const router = { replace: vi.fn(), push: vi.fn() };
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: true } },
routeQuery: { tab: 'subscriptions', success: 'true', type: 'extras' },
router,
});
await flushPromises();
expect(wrapper.text()).toContain('Pack credited to your balance');
});
it('shows extras success copy when packPurchased=true string is present', async () => {
const router = { replace: vi.fn(), push: vi.fn() };
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: true } },
routeQuery: { tab: 'subscriptions', packPurchased: 'true' },
router,
});
await flushPromises();
expect(wrapper.text()).toContain('Pack credited to your balance');
});
it('does NOT show success banner when packPurchased=false string is present', async () => {
const router = { replace: vi.fn(), push: vi.fn() };
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: true } },
routeQuery: { tab: 'subscriptions', packPurchased: 'false' },
router,
});
await flushPromises();
expect(wrapper.text()).not.toContain('successfully');
expect(router.replace).not.toHaveBeenCalled();
});
});
// ─── Suite 6: Ledger pagination ──────────────────────────────────────────────
describe('BillingSubscriptionsComponent — ledger pagination', () => {
let wrapper;
let store;
beforeEach(() => {
setActivePinia(createPinia());
vi.clearAllMocks();
store = useBillingStore();
seedMeterStore(store);
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
});
it('onLedgerPageChange forwards the page number', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
const fetchSpy = vi.spyOn(store, 'fetchExtrasLedger').mockResolvedValue({ entries: [], total: 0, page: 2, limit: 20 });
await wrapper.vm.onLedgerPageChange(2);
expect(fetchSpy).toHaveBeenCalledWith({ page: 2, limit: 20 });
});
it('extrasLedger computed falls back to empty state when store value is null', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
expect(wrapper.vm.extrasLedger.entries).toEqual([]);
expect(wrapper.vm.extrasLedger.total).toBe(0);
});
});
// ─── Suite 7: P1-1 — Subscription fetch error state ─────────────────────────
describe('BillingSubscriptionsComponent — subscription fetch error (P1-1)', () => {
let wrapper;
let store;
beforeEach(() => {
setActivePinia(createPinia());
vi.clearAllMocks();
sessionStorage.clear();
store = useBillingStore();
seedMeterStore(store);
// Simulate a failed fetchSubscription: error set, subscription remains null
store.subscription = null;
store.subscriptionError = 'Network error';
vi.spyOn(store, 'fetchSubscription').mockRejectedValue(new Error('Network error'));
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
sessionStorage.clear();
});
it('shows error card instead of free-plan fallback when subscriptionError is set', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
// Error card present
expect(wrapper.find('[role="alert"]').exists()).toBe(true);
// Must NOT show the free-plan "Upgrade" CTA or free plan text
expect(wrapper.text()).not.toContain("You're on the free plan");
});
it('error card has aria-live="assertive" for a11y (P1-1)', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
const alert = wrapper.find('[role="alert"]');
expect(alert.exists()).toBe(true);
expect(alert.attributes('aria-live')).toBe('assertive');
});
it('error card contains retry button', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
const retryBtn = wrapper.findAll('.v-btn').find((b) => b.text().toLowerCase().includes('retry'));
expect(retryBtn).toBeDefined();
});
it('retry button calls fetchSubscription again', async () => {
const fetchSpy = vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
store.subscriptionError = 'Network error';
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
await wrapper.vm.retryFetchSubscription();
expect(fetchSpy).toHaveBeenCalled();
});
it('clears error card when retry succeeds and subscription loads', async () => {
const sub = { plan: 'pro', status: 'active' };
vi.spyOn(store, 'fetchSubscription').mockImplementation(async () => {
store.subscription = sub;
store.subscriptionError = null;
});
store.subscriptionError = 'Network error';
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
await wrapper.vm.retryFetchSubscription();
await flushPromises();
expect(wrapper.find('[role="alert"]').exists()).toBe(false);
});
});
// ─── Suite 8: P1-2 — Checkout polling after Stripe success ───────────────────
describe('BillingSubscriptionsComponent — checkout success polling (P1-2)', () => {
let wrapper;
let store;
beforeEach(() => {
setActivePinia(createPinia());
vi.useFakeTimers();
vi.clearAllMocks();
sessionStorage.clear();
store = useBillingStore();
seedMeterStore(store);
store.subscription = null;
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
vi.useRealTimers();
sessionStorage.clear();
});
it('shows processing spinner when ?success=true (non-extras)', async () => {
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { tab: 'subscriptions', success: 'true' },
});
await flushPromises();
expect(wrapper.vm.checkoutProcessing).toBe(true);
});
it('transitions to success message when subscription activates on 3rd poll', async () => {
let callCount = 0;
vi.spyOn(store, 'fetchSubscription').mockImplementation(async () => {
callCount += 1;
if (callCount >= 3) {
store.subscription = { plan: 'starter', status: 'active', stripeSubscriptionId: 'sub_new123' };
store.subscriptionError = null;
}
});
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { tab: 'subscriptions', success: 'true' },
});
await flushPromises();
expect(wrapper.vm.checkoutProcessing).toBe(true);
// Advance 2 polls (4s)
await vi.advanceTimersByTimeAsync(4000);
await flushPromises();
// 3rd poll activates subscription
await vi.advanceTimersByTimeAsync(2000);
await flushPromises();
expect(wrapper.vm.checkoutProcessing).toBe(false);
expect(wrapper.vm.paymentSuccessMessage).toContain('Subscription activated successfully');
});
it('shows timeout message after 8 polls without state change', async () => {
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { tab: 'subscriptions', success: 'true' },
});
await flushPromises();
// Advance 8 × 2s = 16s
await vi.advanceTimersByTimeAsync(16000);
await flushPromises();
expect(wrapper.vm.checkoutProcessing).toBe(false);
expect(wrapper.vm.checkoutTimeout).toBe(true);
});
it('timeout message renders in template with refresh button', async () => {
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { tab: 'subscriptions', success: 'true' },
});
await flushPromises();
await vi.advanceTimersByTimeAsync(16000);
await flushPromises();
expect(wrapper.text()).toContain('Payment received');
const refreshBtn = wrapper.findAll('.v-btn').find((b) => b.text().toLowerCase().includes('refresh'));
expect(refreshBtn).toBeDefined();
});
it('retryFetchSubscription clears checkoutTimeout when refresh confirms active subscription', async () => {
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { tab: 'subscriptions', success: 'true' },
});
await flushPromises();
// Force timeout
await vi.advanceTimersByTimeAsync(16000);
await flushPromises();
expect(wrapper.vm.checkoutTimeout).toBe(true);
// Manual refresh confirms active sub
vi.spyOn(store, 'fetchSubscription').mockImplementation(async () => {
store.subscription = { plan: 'starter', status: 'active', stripeSubscriptionId: 'sub_123' };
store.subscriptionError = null;
return store.subscription;
});
await wrapper.vm.retryFetchSubscription();
expect(wrapper.vm.checkoutTimeout).toBe(false);
expect(wrapper.vm.paymentSuccessMessage).toContain('Subscription activated successfully');
});
it('plan change detected as activation (upgrade with same stripeSubscriptionId)', async () => {
store.subscription = { plan: 'starter', status: 'active', stripeSubscriptionId: 'sub_same' };
let callCount = 0;
vi.spyOn(store, 'fetchSubscription').mockImplementation(async () => {
callCount += 1;
if (callCount >= 2) {
store.subscription = { plan: 'pro', status: 'active', stripeSubscriptionId: 'sub_same' };
store.subscriptionError = null;
}
});
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { tab: 'subscriptions', success: 'true' },
});
await flushPromises();
// 2nd poll detects plan change
await vi.advanceTimersByTimeAsync(4000);
await flushPromises();
expect(wrapper.vm.checkoutProcessing).toBe(false);
expect(wrapper.vm.paymentSuccessMessage).toContain('Subscription activated successfully');
});
it('extras purchase shows success immediately without subscription polling', async () => {
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: true } },
routeQuery: { tab: 'subscriptions', success: 'true', type: 'extras' },
});
await flushPromises();
// No polling active for extras
expect(wrapper.vm.checkoutProcessing).toBe(false);
expect(wrapper.vm.checkoutPollCount).toBe(0);
expect(wrapper.vm.paymentSuccessMessage).toContain('Pack credited to your balance');
});
});
// ─── Suite 9: meterError — centralized snackbar (no inline v-alert) ──────────
// meterError is now surfaced via lib/services/axios.js interceptor → centralized snackbar.
// The subscriptions component no longer renders an inline v-alert for meter errors.
describe('BillingSubscriptionsComponent — meterError (centralized snackbar, no inline alert)', () => {
let wrapper;
let store;
beforeEach(() => {
setActivePinia(createPinia());
vi.clearAllMocks();
sessionStorage.clear();
store = useBillingStore();
seedMeterStore(store);
store.subscription = { status: 'active', plan: 'starter', currentPeriodEnd: new Date().toISOString() };
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
});
it('does NOT render inline meter error alert (meterError surfaced via centralized snackbar)', async () => {
// Even when meter fetch fails, no inline v-alert appears in this component.
vi.spyOn(store, 'fetchUsageMeter').mockRejectedValueOnce(new Error('meter fetch failed'));
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
// Only status-banner alerts are acceptable (checkoutProcessing/timeout/paymentSuccess)
// No "Could not refresh usage" inline alert
expect(wrapper.text()).not.toContain('Could not refresh usage');
});
it('does NOT render inline v-alert on meter error in meterMode=false', async () => {
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: false } } });
await flushPromises();
// No meter-related alert should render in legacy mode
expect(wrapper.text()).not.toContain('Could not refresh usage');
});
it('combinedPool computed equals meterQuota + meterExtras + meterUsed', async () => {
// useMeter returns values seeded from billingStore.usageMeter
wrapper = mountSubscriptions({ serverConfig: { billing: { meterMode: true } } });
await flushPromises();
// mockUsageMeterNormal: meterUsed=120, meterQuota=500, extrasRemaining=50
// combinedPool = 500 + 50 + 120 = 670
expect(wrapper.vm.combinedPool).toBe(670);
});
});
// ─── Suite 10: V5 P1 — F5 mid-polling sessionStorage recovery ────────────────
describe('BillingSubscriptionsComponent — F5 polling recovery (V5 P1)', () => {
let wrapper;
let store;
const SESSION_KEY = 'billing.checkout.polling';
beforeEach(() => {
setActivePinia(createPinia());
vi.useFakeTimers();
vi.clearAllMocks();
sessionStorage.clear();
store = useBillingStore();
seedMeterStore(store);
store.subscription = null;
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
vi.useRealTimers();
sessionStorage.clear();
});
it('persists polling session to sessionStorage with snapshot fields when ?success=true starts polling', async () => {
store.subscription = { status: 'active', plan: 'starter', stripeSubscriptionId: 'sub_before' };
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { success: 'true' },
});
await flushPromises();
const raw = sessionStorage.getItem(SESSION_KEY);
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw);
expect(parsed).toHaveProperty('startedAt');
expect(typeof parsed.startedAt).toBe('number');
// Snapshot fields should be persisted for reliable F5 recovery
expect(parsed).toHaveProperty('snapshotId', 'sub_before');
expect(parsed).toHaveProperty('snapshotStatus', 'active');
expect(parsed).toHaveProperty('snapshotPlan', 'starter');
});
it('resumes polling and restores snapshots from sessionStorage (F5 mid-polling)', async () => {
// Simulate 4 seconds elapsed — still within the 16s window
// Include snapshot fields so baseline is correctly restored
sessionStorage.setItem(SESSION_KEY, JSON.stringify({
startedAt: Date.now() - 4000,
snapshotId: 'sub_before_f5',
snapshotStatus: 'active',
snapshotPlan: 'starter',
}));
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
// Mount without ?success query — simulates F5
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: {},
});
await flushPromises();
// Should resume processing state
expect(wrapper.vm.checkoutProcessing).toBe(true);
// Poll count should start at 2 (4000ms / 2000ms per poll)
expect(wrapper.vm.checkoutPollCount).toBe(2);
// Snapshots restored from storage — not from null store state
expect(wrapper.vm.checkoutPollSnapshotId).toBe('sub_before_f5');
expect(wrapper.vm.checkoutPollSnapshotStatus).toBe('active');
expect(wrapper.vm.checkoutPollSnapshotPlan).toBe('starter');
});
it('shows processing banner when polling is resumed after F5', async () => {
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ startedAt: Date.now() - 2000 }));
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: {},
});
await flushPromises();
expect(wrapper.text()).toContain('Processing your payment');
});
it('does NOT resume polling when sessionStorage contains malformed startedAt', async () => {
// Store malformed data with invalid startedAt
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ startedAt: 'not-a-number' }));
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: {},
});
await flushPromises();
expect(wrapper.vm.checkoutProcessing).toBe(false);
// Session key should be cleared after invalid data detected
expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();
});
it('does NOT resume polling when sessionStorage entry is expired (F5 after timeout)', async () => {
// Simulate 20 seconds elapsed — beyond the 16s window
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ startedAt: Date.now() - 20000 }));
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: {},
});
await flushPromises();
expect(wrapper.vm.checkoutProcessing).toBe(false);
// Session key should be cleared
expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();
});
it('clears sessionStorage on successful subscription activation', async () => {
sessionStorage.setItem(SESSION_KEY, JSON.stringify({
startedAt: Date.now(),
snapshotId: null,
snapshotStatus: null,
snapshotPlan: null,
}));
let callCount = 0;
vi.spyOn(store, 'fetchSubscription').mockImplementation(async () => {
callCount += 1;
if (callCount >= 1) {
store.subscription = { plan: 'starter', status: 'active', stripeSubscriptionId: 'sub_new' };
}
});
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: {},
});
await flushPromises();
await vi.advanceTimersByTimeAsync(2000);
await flushPromises();
expect(sessionStorage.getItem(SESSION_KEY)).toBeNull();
});
it('clears sessionStorage on polling timeout', async () => {
vi.spyOn(store, 'fetchSubscription').mockResolvedValue(null);
wrapper = mountSubscriptions({
serverConfig: { billing: { meterMode: false } },
routeQuery: { success: 'true' },
});
await flushPromises();
// Advance 8 × 2s to exhaust polls
await vi.advanceTimersByTimeAsync(16000);
await flushPromises();