From bfef5457b52f68a3f24ef7a279e191f98c8f352b Mon Sep 17 00:00:00 2001 From: Amp Date: Tue, 15 Sep 2026 02:33:36 +0000 Subject: [PATCH 1/4] test: replace partial billing factories with a typed manual mock Amp-Thread-ID: https://ampcode.com/threads/T-01a0a2e1-7717-749d-9830-826a3d4b3bd5 --- .fallowrc.jsonc | 1 + .../content/setting/CreditsPanel.test.ts | 35 +++----- .../topbar/CurrentUserPopoverLegacy.test.ts | 30 ++++--- .../topbar/TopbarSubscribeButton.test.ts | 53 ++++------- .../billing/__mocks__/useBillingContext.ts | 47 ++++++++++ .../CloudSubscriptionRedirectView.test.ts | 49 +++++------ .../components/FreeTierQuota.test.ts | 14 +-- .../components/SubscribeToRun.test.ts | 12 +-- .../SubscriptionFooterLinks.test.ts | 12 +-- .../useAccountPreconditionDialog.test.ts | 19 ++-- .../usePaymentReturnUrlLoader.test.ts | 12 ++- .../usePricingTableUrlLoader.test.ts | 35 ++++---- .../useSubscriptionActions.test.ts | 18 ++-- .../settings/components/SettingDialog.test.ts | 5 +- .../composables/useSettingsDialog.test.ts | 19 ++-- .../components/InviteMembersForm.test.ts | 20 ++--- .../components/PricingTableWorkspace.test.ts | 16 ++-- .../SubscriptionPanelContentWorkspace.test.ts | 78 ++++++++--------- .../SubscriptionSuccessWorkspace.test.ts | 25 +++--- ...TopUpCreditsDialogContentWorkspace.test.ts | 87 ++++++++++--------- .../dialogs/InviteMemberDialogContent.test.ts | 31 +++---- .../composables/useResubscribe.test.ts | 31 +++---- .../stores/billingOperationStore.test.ts | 30 +++---- .../tour/useFirstRunTourController.test.ts | 18 ++-- .../linearMode/LinearControls.test.ts | 19 ++-- src/services/dialogService.downgrade.test.ts | 19 ++-- src/services/dialogService.renderer.test.ts | 21 +++-- 27 files changed, 376 insertions(+), 380 deletions(-) create mode 100644 src/composables/billing/__mocks__/useBillingContext.ts diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc index f1d2223650a..107eeceda5f 100644 --- a/.fallowrc.jsonc +++ b/.fallowrc.jsonc @@ -6,6 +6,7 @@ "entry": [ "src/main.ts", "src/platform/telemetry/__mocks__/index.ts", + "src/composables/billing/__mocks__/useBillingContext.ts", "index.html", "scripts/**/*.{js,ts}", "apps/website/src/scripts/**/*.ts", diff --git a/src/components/dialog/content/setting/CreditsPanel.test.ts b/src/components/dialog/content/setting/CreditsPanel.test.ts index 5f4bb29194a..704ee2e89f6 100644 --- a/src/components/dialog/content/setting/CreditsPanel.test.ts +++ b/src/components/dialog/content/setting/CreditsPanel.test.ts @@ -1,31 +1,16 @@ import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { defineComponent, h, nextTick } from 'vue' +import { computed, defineComponent, h, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' import type { BalanceInfo } from '@/composables/billing/types' +import { useBillingContext } from '@/composables/billing/useBillingContext' import CreditsPanel from './CreditsPanel.vue' -const billingMocks = vi.hoisted(() => ({ - balance: { value: null as BalanceInfo | null }, - manageSubscription: vi.fn() -})) -vi.mock( - import('@/composables/billing/useBillingContext'), - async () => { - const { ref } = await import('vue') - const balance = ref(null) - Object.defineProperty(billingMocks, 'balance', { get: () => balance }) - return { - useBillingContext: () => ({ - balance, - manageSubscription: billingMocks.manageSubscription - }) - } - } -) +const balance = ref(null) +vi.mock(import('@/composables/billing/useBillingContext')) const refreshActivity = vi.hoisted(() => vi.fn()) vi.mock(import('./UsageLogsTable.vue'), async () => { @@ -85,7 +70,11 @@ function makeBalance(amountMicros: number): BalanceInfo { describe('CreditsPanel', () => { beforeEach(() => { - billingMocks.balance.value = null + balance.value = null + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + balance: computed(() => balance.value) + } as const) }) function renderComponent() { @@ -100,17 +89,17 @@ describe('CreditsPanel', () => { await user.click(screen.getByRole('button', { name: /Invoice History/ })) - expect(billingMocks.manageSubscription).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() }) it('refreshes activity on a balance change but not on first hydration', async () => { renderComponent() - billingMocks.balance.value = makeBalance(5000) + balance.value = makeBalance(5000) await nextTick() expect(refreshActivity).not.toHaveBeenCalled() - billingMocks.balance.value = makeBalance(9000) + balance.value = makeBalance(9000) await nextTick() expect(refreshActivity).toHaveBeenCalledOnce() }) diff --git a/src/components/topbar/CurrentUserPopoverLegacy.test.ts b/src/components/topbar/CurrentUserPopoverLegacy.test.ts index a70abe4a721..b90dcd96baa 100644 --- a/src/components/topbar/CurrentUserPopoverLegacy.test.ts +++ b/src/components/topbar/CurrentUserPopoverLegacy.test.ts @@ -1,8 +1,9 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { getActivePinia } from 'pinia' import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' -import { h, ref } from 'vue' +import { h, ref, computed } from 'vue' import { createI18n } from 'vue-i18n' import { formatCreditsFromCents } from '@/base/credits/comfyCredits' @@ -25,6 +26,18 @@ vi.mock(import('@/platform/settings/composables/useSettingsDialog'), () => ({ const originalWindowOpen = window.open beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + canAccessSubscriptionFeatures: computed( + () => mockCanAccessSubscriptionFeatures.value + ), + tier: computed(() => mockTier.value), + subscription: computed(() => mockSubscription.value), + balance: computed(() => mockBalance.value), + isLoading: mockIsLoading, + isTeamPlan: computed(() => mockIsTeamPlan.value) + } as const) + window.open = vi.fn() }) @@ -65,7 +78,6 @@ function makeSubscription( } } -const mockFetchBalance = vi.fn().mockResolvedValue(undefined) const mockCanAccessSubscriptionFeatures = ref(true) const mockTier = ref('CREATOR') const mockSubscription = ref(makeSubscription()) @@ -75,17 +87,7 @@ const mockIsTeamPlan = ref(false) const mockCanTopUp = ref(true) const mockCanSubscribeSelfServe = ref(false) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: vi.fn(() => ({ - canAccessSubscriptionFeatures: mockCanAccessSubscriptionFeatures, - tier: mockTier, - subscription: mockSubscription, - balance: mockBalance, - isLoading: mockIsLoading, - isTeamPlan: mockIsTeamPlan, - fetchBalance: mockFetchBalance - })) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('@/platform/workspace/composables/useBillingCapabilities'), @@ -174,7 +176,7 @@ describe('CurrentUserPopoverLegacy', () => { it('fetches the balance through the billing facade on mount', () => { renderComponent() - expect(mockFetchBalance).toHaveBeenCalled() + expect(useBillingContext().fetchBalance).toHaveBeenCalled() }) describe('subscription tier badge', () => { diff --git a/src/components/topbar/TopbarSubscribeButton.test.ts b/src/components/topbar/TopbarSubscribeButton.test.ts index e63583bf102..2f588b68135 100644 --- a/src/components/topbar/TopbarSubscribeButton.test.ts +++ b/src/components/topbar/TopbarSubscribeButton.test.ts @@ -1,6 +1,8 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useBillingContext } from '@/composables/billing/useBillingContext' +import { useSubscribeToRunPromptPresence } from '@/platform/cloud/subscription/composables/useSubscribeCtaPresence' import { getActivePinia } from 'pinia' -import { nextTick } from 'vue' +import { describe, expect, it, vi } from 'vitest' +import { computed, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' import { render, screen } from '@testing-library/vue' @@ -28,33 +30,9 @@ vi.mock( }) ) -const mockState = vi.hoisted(() => ({ - holder: null as null | { isFreeTier: boolean; promptMounted: boolean } -})) - -vi.mock( - import('@/composables/billing/useBillingContext'), - async () => { - const { computed, reactive } = await import('vue') - mockState.holder ??= reactive({ isFreeTier: true, promptMounted: false }) - return { - useBillingContext: vi.fn(() => ({ - isFreeTier: computed(() => mockState.holder!.isFreeTier) - })) - } - } -) - -vi.mock( - import('@/platform/cloud/subscription/composables/useSubscribeCtaPresence'), - async () => { - const { computed, reactive } = await import('vue') - mockState.holder ??= reactive({ isFreeTier: true, promptMounted: false }) - return { - useSubscribeToRunPromptPresence: () => - computed(() => mockState.holder!.promptMounted) - } - } +vi.mock(import('@/composables/billing/useBillingContext')) +vi.mock( + import('@/platform/cloud/subscription/composables/useSubscribeCtaPresence') ) vi.mock(import('firebase/app'), () => ({ @@ -70,7 +48,11 @@ vi.mock(import('firebase/auth'), () => ({ signOut: vi.fn() })) -function renderComponent() { +function renderComponent(promptMounted = computed(() => false)) { + const billing = useBillingContext() + billing.isFreeTier = computed(() => true) + vi.mocked(useBillingContext).mockReturnValue(billing) + vi.mocked(useSubscribeToRunPromptPresence).mockReturnValue(promptMounted) const i18n = createI18n({ legacy: false, locale: 'en', @@ -85,11 +67,6 @@ function renderComponent() { } describe('TopbarSubscribeButton', () => { - beforeEach(() => { - mockState.holder!.isFreeTier = true - mockState.holder!.promptMounted = false - }) - it('renders on cloud when isFreeTier is true', () => { mockIsCloud.value = true renderComponent() @@ -98,13 +75,13 @@ describe('TopbarSubscribeButton', () => { it('yields while a Run-slot subscribe prompt is mounted, and returns when it unmounts', async () => { mockIsCloud.value = true - mockState.holder!.promptMounted = true - renderComponent() + const promptMounted = ref(true) + renderComponent(computed(() => promptMounted.value)) expect( screen.queryByTestId('topbar-subscribe-button') ).not.toBeInTheDocument() - mockState.holder!.promptMounted = false + promptMounted.value = false await nextTick() expect(screen.getByTestId('topbar-subscribe-button')).toBeInTheDocument() }) diff --git a/src/composables/billing/__mocks__/useBillingContext.ts b/src/composables/billing/__mocks__/useBillingContext.ts new file mode 100644 index 00000000000..403884dd13b --- /dev/null +++ b/src/composables/billing/__mocks__/useBillingContext.ts @@ -0,0 +1,47 @@ +import { beforeEach, vi } from 'vitest' +import { computed, ref } from 'vue' + +import type { useBillingContext as realUseBillingContext } from '../useBillingContext' + +export const useBillingContext = vi.fn() + +beforeEach(() => { + useBillingContext.mockReturnValue({ + type: computed(() => 'legacy'), + isInitialized: ref(false), + isLoading: ref(false), + error: ref(null), + subscription: computed(() => null), + balance: computed(() => null), + plans: computed(() => []), + currentPlanSlug: computed(() => null), + teamCreditStops: computed(() => null), + currentTeamCreditStop: computed(() => null), + maxSeats: computed(() => null), + occupiedSeats: computed(() => null), + canAccessSubscriptionFeatures: computed(() => false), + isFreeTier: computed(() => false), + billingStatus: computed(() => null), + subscriptionStatus: computed(() => null), + tier: computed(() => null), + renewalDate: computed(() => null), + isLegacyTeamPlan: computed(() => false), + isTeamPlan: computed(() => false), + canRunWorkflows: computed(() => false), + showsSubscribeToRunPrompt: computed(() => false), + getMaxSeats: vi.fn(() => 1), + initialize: vi.fn(async () => {}), + fetchStatus: vi.fn(async () => {}), + fetchBalance: vi.fn(async () => {}), + subscribe: vi.fn(async () => {}), + previewSubscribe: vi.fn(async () => null), + manageSubscription: vi.fn(async () => {}), + cancelSubscription: vi.fn(async () => {}), + resubscribe: vi.fn(async () => {}), + topup: vi.fn(async () => {}), + fetchPlans: vi.fn(async () => {}), + requireActiveSubscription: vi.fn(async () => {}), + showSubscriptionDialog: vi.fn(), + reconcileSubscriptionSuccess: vi.fn(async () => {}) + } as const) +}) diff --git a/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts b/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts index 8e7678df6fd..3d826b51190 100644 --- a/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts +++ b/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts @@ -1,8 +1,10 @@ import { render, screen } from '@testing-library/vue' import { beforeEach, describe, expect, test, vi } from 'vitest' +import { computed, ref } from 'vue' import { createI18n } from 'vue-i18n' import { useAuthActions } from '@/composables/auth/useAuthActions' +import { useBillingContext } from '@/composables/billing/useBillingContext' import type { TeamCreditStops } from '@/platform/workspace/api/workspaceApi' import CloudSubscriptionRedirectView from './CloudSubscriptionRedirectView.vue' @@ -34,18 +36,10 @@ vi.mock(import('@/composables/useErrorHandling'), () => ({ }) })) -const subscriptionMocks = vi.hoisted(() => ({ - canAccessSubscriptionFeatures: { value: false }, - isInitialized: { value: true }, - teamCreditStops: { value: null as TeamCreditStops | null }, - initialize: vi.fn(), - fetchPlans: vi.fn(), - manageSubscription: vi.fn() -})) +const canAccessSubscriptionFeatures = ref(false) +const teamCreditStops = ref(null) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => subscriptionMocks -})) +vi.mock(import('@/composables/billing/useBillingContext')) const mockShowPricingTable = vi.hoisted(() => vi.fn()) vi.mock( @@ -130,12 +124,17 @@ const mountView = async (query: Record) => { describe('CloudSubscriptionRedirectView', () => { beforeEach(() => { mockQuery = {} - subscriptionMocks.canAccessSubscriptionFeatures.value = false - subscriptionMocks.isInitialized.value = true - subscriptionMocks.teamCreditStops.value = TEAM_CREDIT_STOPS - subscriptionMocks.initialize.mockResolvedValue(undefined) - subscriptionMocks.fetchPlans.mockResolvedValue(undefined) - subscriptionMocks.manageSubscription.mockResolvedValue(undefined) + canAccessSubscriptionFeatures.value = false + teamCreditStops.value = TEAM_CREDIT_STOPS + const billing = useBillingContext() + Object.assign(billing, { + isInitialized: ref(true), + canAccessSubscriptionFeatures: computed( + () => canAccessSubscriptionFeatures.value + ), + teamCreditStops: computed(() => teamCreditStops.value) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) }) test('redirects to home when subscriptionType is missing', async () => { @@ -179,12 +178,12 @@ describe('CloudSubscriptionRedirectView', () => { }) test('opens billing portal when subscription is already active', async () => { - subscriptionMocks.canAccessSubscriptionFeatures.value = true + canAccessSubscriptionFeatures.value = true await mountView({ tier: 'creator' }) expect(mockRouterPush).not.toHaveBeenCalledWith('/') - expect(subscriptionMocks.manageSubscription).toHaveBeenCalledTimes(1) + expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(1) expect(useAuthActions().accessBillingPortal).not.toHaveBeenCalled() expect(mockShowPricingTable).not.toHaveBeenCalled() }) @@ -228,9 +227,9 @@ describe('CloudSubscriptionRedirectView', () => { }) test('opens the generic team pricing table when plan loading fails', async () => { - subscriptionMocks.teamCreditStops.value = null + teamCreditStops.value = null const plansError = new Error('plans down') - subscriptionMocks.fetchPlans.mockRejectedValue(plansError) + vi.mocked(useBillingContext().fetchPlans).mockRejectedValue(plansError) await mountView({ tier: 'team', stop: 'team_700', cycle: 'yearly' }) @@ -264,11 +263,11 @@ describe('CloudSubscriptionRedirectView', () => { }) test('routes a personal tier in an active Team workspace to workspace subscription management', async () => { - subscriptionMocks.canAccessSubscriptionFeatures.value = true + canAccessSubscriptionFeatures.value = true await mountView({ tier: 'creator', cycle: 'yearly' }) - expect(subscriptionMocks.manageSubscription).toHaveBeenCalledTimes(1) + expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(1) expect(useAuthActions().accessBillingPortal).not.toHaveBeenCalled() expect( legacyCheckoutMocks.performSubscriptionCheckout @@ -277,11 +276,11 @@ describe('CloudSubscriptionRedirectView', () => { }) test('routes an active founder subscription to facade management', async () => { - subscriptionMocks.canAccessSubscriptionFeatures.value = true + canAccessSubscriptionFeatures.value = true await mountView({ tier: 'founder' }) - expect(subscriptionMocks.manageSubscription).toHaveBeenCalledTimes(1) + expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(1) expect(mockRouterPush).not.toHaveBeenCalled() expect(mockShowPricingTable).not.toHaveBeenCalled() }) diff --git a/src/platform/cloud/subscription/components/FreeTierQuota.test.ts b/src/platform/cloud/subscription/components/FreeTierQuota.test.ts index 1f28fdcab9b..903d0ee9ccc 100644 --- a/src/platform/cloud/subscription/components/FreeTierQuota.test.ts +++ b/src/platform/cloud/subscription/components/FreeTierQuota.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { render, screen } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { computed, nextTick, ref } from 'vue' @@ -7,14 +8,8 @@ import FreeTierQuota from './FreeTierQuota.vue' const mockIsFreeTier = ref(true) const mockAvailable = ref(3) -const mockShowSubscriptionDialog = vi.fn() -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - isFreeTier: mockIsFreeTier, - showSubscriptionDialog: mockShowSubscriptionDialog - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('@/platform/cloud/subscription/composables/useFreeTierQuota'), @@ -42,6 +37,11 @@ const i18n = createI18n({ describe('FreeTierQuota', () => { beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + isFreeTier: computed(() => mockIsFreeTier.value) + } as const) + mockIsFreeTier.value = true mockAvailable.value = 3 }) diff --git a/src/platform/cloud/subscription/components/SubscribeToRun.test.ts b/src/platform/cloud/subscription/components/SubscribeToRun.test.ts index 8aebaefba82..bd3301e5b00 100644 --- a/src/platform/cloud/subscription/components/SubscribeToRun.test.ts +++ b/src/platform/cloud/subscription/components/SubscribeToRun.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -6,15 +7,10 @@ import { createI18n } from 'vue-i18n' import SubscribeToRun from './SubscribeToRun.vue' -const mockShowSubscriptionDialog = vi.fn() const mockCanManageSubscription = ref(true) const mockIsMdOrLarger = ref(true) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - showSubscriptionDialog: mockShowSubscriptionDialog - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('@/platform/workspace/composables/useWorkspaceUI'), @@ -101,7 +97,7 @@ describe('SubscribeToRun', () => { await user.click(screen.getByTestId('subscribe-to-run-button')) - expect(mockShowSubscriptionDialog).toHaveBeenCalledOnce() + expect(useBillingContext().showSubscriptionDialog).toHaveBeenCalledOnce() }) it('routes members to the same role-aware dialog on click', async () => { @@ -110,6 +106,6 @@ describe('SubscribeToRun', () => { await user.click(screen.getByTestId('subscribe-to-run-button')) - expect(mockShowSubscriptionDialog).toHaveBeenCalledOnce() + expect(useBillingContext().showSubscriptionDialog).toHaveBeenCalledOnce() }) }) diff --git a/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts b/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts index 5e72621396c..2e6cf10ba21 100644 --- a/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts +++ b/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -9,7 +10,6 @@ import SubscriptionFooterLinks from './SubscriptionFooterLinks.vue' const state = vi.hoisted(() => ({ isCloud: true, - manageSubscription: vi.fn(), handleLearnMoreClick: vi.fn(), handleMessageSupport: vi.fn() })) @@ -24,11 +24,7 @@ vi.mock(import('@/platform/distribution/types'), () => ({ } })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - manageSubscription: state.manageSubscription - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('@/composables/useExternalLink'), () => ({ useExternalLink: () => ({ @@ -134,7 +130,7 @@ describe('SubscriptionFooterLinks', () => { await user.click(screen.getByRole('button', { name: 'Invoice history' })) - expect(state.manageSubscription).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() }) it('hides Invoice history from local users without billing permission', () => { @@ -144,7 +140,7 @@ describe('SubscriptionFooterLinks', () => { expect( screen.queryByRole('button', { name: 'Invoice history' }) ).not.toBeInTheDocument() - expect(state.manageSubscription).not.toHaveBeenCalled() + expect(useBillingContext().manageSubscription).not.toHaveBeenCalled() }) it('opens the platform usage page', async () => { diff --git a/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts b/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts index 385c8f94937..0b5830684d7 100644 --- a/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts +++ b/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it, vi } from 'vitest' +import { useBillingContext } from '@/composables/billing/useBillingContext' + import { useAccountPreconditionDialog } from './useAccountPreconditionDialog' const mockDialogService = { @@ -8,18 +10,11 @@ const mockDialogService = { showTopUpCreditsDialog: vi.fn() } -const mockBilling = { - fetchStatus: vi.fn(), - fetchBalance: vi.fn() -} - vi.mock(import('@/services/dialogService'), () => ({ useDialogService: vi.fn(() => mockDialogService) })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: vi.fn(() => mockBilling) -})) +vi.mock(import('@/composables/billing/useBillingContext')) describe('useAccountPreconditionDialog', () => { it('routes a sign-in precondition to the API sign-in dialog with the node type', () => { @@ -64,14 +59,14 @@ describe('useAccountPreconditionDialog', () => { it('refreshes the billing snapshot on a credit precondition so exhausted-state surfaces converge', () => { useAccountPreconditionDialog().open('credits') - expect(mockBilling.fetchStatus).toHaveBeenCalledTimes(1) - expect(mockBilling.fetchBalance).toHaveBeenCalledTimes(1) + expect(useBillingContext().fetchStatus).toHaveBeenCalledTimes(1) + expect(useBillingContext().fetchBalance).toHaveBeenCalledTimes(1) }) it('does not touch billing state for non-credit preconditions', () => { useAccountPreconditionDialog().open('subscription') - expect(mockBilling.fetchStatus).not.toHaveBeenCalled() - expect(mockBilling.fetchBalance).not.toHaveBeenCalled() + expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() + expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() }) }) diff --git a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts index 0ac559d7b5c..9ba49a55844 100644 --- a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts +++ b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { beforeEach, describe, expect, it, vi } from 'vitest' import { stripPaymentReturnParams } from '@/platform/cloud/subscription/utils/paymentReturnUrl' @@ -5,13 +6,10 @@ import { stripPaymentReturnParams } from '@/platform/cloud/subscription/utils/pa import { usePaymentReturnUrlLoader } from './usePaymentReturnUrlLoader' const mocks = vi.hoisted(() => ({ - fetchStatus: vi.fn().mockResolvedValue(undefined), embeddedCheckoutEnabled: true })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ fetchStatus: mocks.fetchStatus }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('@/composables/useFeatureFlags'), () => ({ useFeatureFlags: () => ({ @@ -41,7 +39,7 @@ describe('usePaymentReturnUrlLoader', () => { await loadPaymentReturnFromUrl() expect(window.location.search).toBe('?workspace=ws-1') - expect(mocks.fetchStatus).toHaveBeenCalledOnce() + expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() }) it('does nothing on an ordinary page load', async () => { @@ -50,7 +48,7 @@ describe('usePaymentReturnUrlLoader', () => { const { loadPaymentReturnFromUrl } = usePaymentReturnUrlLoader() await loadPaymentReturnFromUrl() - expect(mocks.fetchStatus).not.toHaveBeenCalled() + expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() }) it('does not start embedded recovery while the flag is off', async () => { @@ -64,6 +62,6 @@ describe('usePaymentReturnUrlLoader', () => { await usePaymentReturnUrlLoader().loadPaymentReturnFromUrl() - expect(mocks.fetchStatus).not.toHaveBeenCalled() + expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() }) }) diff --git a/src/platform/cloud/subscription/composables/usePricingTableUrlLoader.test.ts b/src/platform/cloud/subscription/composables/usePricingTableUrlLoader.test.ts index 52f7ec1f614..7d1c4ff7549 100644 --- a/src/platform/cloud/subscription/composables/usePricingTableUrlLoader.test.ts +++ b/src/platform/cloud/subscription/composables/usePricingTableUrlLoader.test.ts @@ -1,3 +1,5 @@ +import { computed, ref } from 'vue' +import { useBillingContext } from '@/composables/billing/useBillingContext' import { fromAny } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -44,17 +46,9 @@ vi.mock( const mockPermissions = vi.hoisted(() => ({ value: { canManageSubscription: true } })) -const mockTeamCreditStops = vi.hoisted(() => ({ - value: null as TeamCreditStops | null -})) -const mockFetchPlans = vi.hoisted(() => vi.fn()) +const mockTeamCreditStops = ref(null) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - teamCreditStops: mockTeamCreditStops, - fetchPlans: mockFetchPlans - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) const mockCanOpenPricingSurface = vi.hoisted(() => ({ value: true })) const mockInitializeCapabilities = vi.hoisted(() => @@ -98,13 +92,18 @@ const TEAM_CREDIT_STOPS = { describe('usePricingTableUrlLoader', () => { beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + teamCreditStops: computed(() => mockTeamCreditStops.value) + } as const) + mockRouteQuery.value = {} mockPermissions.value = { canManageSubscription: true } mockCanOpenPricingSurface.value = true mockInitializeCapabilities.mockClear() mockInitializeCapabilities.mockResolvedValue(undefined) mockTeamCreditStops.value = TEAM_CREDIT_STOPS - mockFetchPlans.mockResolvedValue(undefined) + vi.mocked(useBillingContext().fetchPlans).mockResolvedValue(undefined) mockShowPricingTable.mockResolvedValue(undefined) preservedQueryMocks.mergePreservedQueryIntoQuery.mockReturnValue(null) }) @@ -385,14 +384,16 @@ describe('usePricingTableUrlLoader', () => { cycle: 'yearly' } mockTeamCreditStops.value = null - mockFetchPlans.mockImplementationOnce(async () => { - mockTeamCreditStops.value = TEAM_CREDIT_STOPS - }) + vi.mocked(useBillingContext().fetchPlans).mockImplementationOnce( + async () => { + mockTeamCreditStops.value = TEAM_CREDIT_STOPS + } + ) const { loadPricingTableFromUrl } = usePricingTableUrlLoader() await loadPricingTableFromUrl() - expect(mockFetchPlans).toHaveBeenCalledOnce() + expect(useBillingContext().fetchPlans).toHaveBeenCalledOnce() expect(mockShowPricingTable).toHaveBeenCalledWith( expect.objectContaining({ initialCheckout: expect.objectContaining({ @@ -410,7 +411,9 @@ describe('usePricingTableUrlLoader', () => { cycle: 'yearly' } mockTeamCreditStops.value = null - mockFetchPlans.mockRejectedValueOnce(new Error('catalog unavailable')) + vi.mocked(useBillingContext().fetchPlans).mockRejectedValueOnce( + new Error('catalog unavailable') + ) vi.spyOn(console, 'error').mockImplementation(() => {}) const { loadPricingTableFromUrl } = usePricingTableUrlLoader() diff --git a/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts b/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts index 7b0f26df8ad..c1869ad65ad 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useToastStore } from '@/platform/updates/common/toastStore' import { useCommandStore } from '@/stores/commandStore' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -5,8 +6,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useSubscriptionActions } from '@/platform/cloud/subscription/composables/useSubscriptionActions' -const mockBillingFetchBalance = vi.fn() -const mockFetchStatus = vi.fn() const mockShowTopUpCreditsDialog = vi.fn() const mockExecute = vi.fn['execute']>( async () => undefined @@ -23,12 +22,7 @@ vi.mock(import('@/platform/telemetry/reportError'), () => ({ vi.mock(import('@/composables/auth/useAuthActions')) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - fetchBalance: mockBillingFetchBalance, - fetchStatus: mockFetchStatus - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('@/services/dialogService'), () => ({ useDialogService: () => ({ @@ -170,13 +164,15 @@ describe('useSubscriptionActions', () => { const { handleRefresh } = useSubscriptionActions() await handleRefresh() - expect(mockBillingFetchBalance).toHaveBeenCalledOnce() - expect(mockFetchStatus).toHaveBeenCalledOnce() + expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce() + expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(useAuthActions().fetchBalance).not.toHaveBeenCalled() }) it('swallows refresh failures without surfacing a toast', async () => { - mockBillingFetchBalance.mockRejectedValueOnce(new Error('Fetch failed')) + vi.mocked(useBillingContext().fetchBalance).mockRejectedValueOnce( + new Error('Fetch failed') + ) const { handleRefresh } = useSubscriptionActions() await expect(handleRefresh()).resolves.toBeUndefined() diff --git a/src/platform/settings/components/SettingDialog.test.ts b/src/platform/settings/components/SettingDialog.test.ts index 35e9c2bdcf2..7b1bea40bcb 100644 --- a/src/platform/settings/components/SettingDialog.test.ts +++ b/src/platform/settings/components/SettingDialog.test.ts @@ -16,7 +16,6 @@ const searchMocks = vi.hoisted(() => ({ searchQuery: null as unknown as Ref, searchResultsCategories: null as unknown as Ref> })) -const mockFetchBalance = vi.hoisted(() => vi.fn()) vi.mock( import('@/platform/settings/composables/useSettingUI'), @@ -64,9 +63,7 @@ vi.mock( }) ) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ fetchBalance: mockFetchBalance }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('@/platform/telemetry/searchQuery/useSearchQueryTracking'), diff --git a/src/platform/settings/composables/useSettingsDialog.test.ts b/src/platform/settings/composables/useSettingsDialog.test.ts index 8448a1464b0..514aea1987a 100644 --- a/src/platform/settings/composables/useSettingsDialog.test.ts +++ b/src/platform/settings/composables/useSettingsDialog.test.ts @@ -1,3 +1,5 @@ +import { computed } from 'vue' +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useDialogStore } from '@/stores/dialogStore' /** * Settings dialog migration regression net: `useSettingsDialog().show()` must @@ -22,13 +24,16 @@ vi.mock(import('@/i18n'), () => ({ vi.mock(import('@/platform/telemetry')) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - canAccessSubscriptionFeatures: { value: true }, - isFreeTier: { value: false }, - type: { value: 'legacy' } - }) -})) +beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + canAccessSubscriptionFeatures: computed(() => true), + isFreeTier: computed(() => false), + type: computed(() => 'legacy') + } as const) +}) + +vi.mock(import('@/composables/billing/useBillingContext')) import { useSettingsDialog } from '@/platform/settings/composables/useSettingsDialog' diff --git a/src/platform/workspace/components/InviteMembersForm.test.ts b/src/platform/workspace/components/InviteMembersForm.test.ts index e3c401b374f..59b45cd75d4 100644 --- a/src/platform/workspace/components/InviteMembersForm.test.ts +++ b/src/platform/workspace/components/InviteMembersForm.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { render, screen, waitFor } from '@testing-library/vue' import userEvent from '@testing-library/user-event' @@ -10,14 +11,11 @@ import InviteMembersForm from './InviteMembersForm.vue' import type { WorkspacePendingInvite } from '@/platform/workspace/stores/teamWorkspaceStore' -const { mockFetchStatus, mockToastAdd } = vi.hoisted(() => ({ - mockFetchStatus: vi.fn(), +const { mockToastAdd } = vi.hoisted(() => ({ mockToastAdd: vi.fn() })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ fetchStatus: mockFetchStatus }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('primevue/usetoast'), // eslint-disable-line primevue-removal/no-imports @@ -76,7 +74,7 @@ describe('InviteMembersForm', () => { vi.mocked(useTeamWorkspaceStore().fetchPendingInvites).mockResolvedValue([ ...useTeamWorkspaceStore().pendingInvites ]) - mockFetchStatus.mockResolvedValue(undefined) + vi.mocked(useTeamWorkspaceStore().createInvite).mockImplementation( async (email: string) => pendingInviteFor(email) ) @@ -123,13 +121,15 @@ describe('InviteMembersForm', () => { source: 'post_upgrade_success', count: 2 }) - expect(mockFetchStatus).toHaveBeenCalledOnce() + expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(emitted().submitted).toEqual([[['a@b.com', 'c@d.com']]]) }) it('completes submission when the billing refresh fails', async () => { const refreshError = new Error('refresh failed') - mockFetchStatus.mockRejectedValueOnce(refreshError) + vi.mocked(useBillingContext().fetchStatus).mockRejectedValueOnce( + refreshError + ) const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) const { user, emitted } = renderForm() @@ -138,7 +138,7 @@ describe('InviteMembersForm', () => { await waitFor(() => expect(emitted().submitted).toEqual([[['a@b.com']]])) expect(submitButton()).toBeEnabled() - expect(mockFetchStatus).toHaveBeenCalledOnce() + expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() await waitFor(() => expect(consoleError).toHaveBeenCalledWith(refreshError)) }) @@ -255,7 +255,7 @@ describe('InviteMembersForm', () => { ) expect(emitted().submitted).toBeUndefined() expect(useTelemetry()?.trackWorkspaceInviteSent).not.toHaveBeenCalled() - expect(mockFetchStatus).not.toHaveBeenCalled() + expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() }) it('keeps over-limit chips visible and blocks submission', async () => { diff --git a/src/platform/workspace/components/PricingTableWorkspace.test.ts b/src/platform/workspace/components/PricingTableWorkspace.test.ts index 6d1682f3c3a..945cce95119 100644 --- a/src/platform/workspace/components/PricingTableWorkspace.test.ts +++ b/src/platform/workspace/components/PricingTableWorkspace.test.ts @@ -6,21 +6,14 @@ import { computed, nextTick } from 'vue' import { createI18n } from 'vue-i18n' import Button from '@/components/ui/button/Button.vue' +import { useBillingContext } from '@/composables/billing/useBillingContext' import enMessages from '@/locales/en/main.json' import type { Plan } from '@/platform/workspace/api/workspaceApi' import PricingTableWorkspace from '@/platform/workspace/components/PricingTableWorkspace.vue' const state = vi.hoisted(() => ({ plans: [] as Plan[] })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - plans: computed(() => state.plans), - currentPlanSlug: computed(() => null), - fetchPlans: vi.fn(), - subscription: computed(() => null), - getMaxSeats: () => 5 - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) function apiPlan( tier: Plan['tier'], @@ -80,6 +73,11 @@ beforeEach(() => { describe('PricingTableWorkspace credit allotment copy', () => { beforeEach(() => { state.plans = [] + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + plans: computed(() => state.plans) + } as const) + vi.mocked(useBillingContext().getMaxSeats).mockReturnValue(5) }) it('shows the catalog grant in preference to twelve static months', () => { diff --git a/src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts b/src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts index d6fb507bfe0..6d6a377288d 100644 --- a/src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts +++ b/src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { getActivePinia } from 'pinia' import { toRef, computed, ref } from 'vue' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' @@ -103,9 +104,6 @@ const mockCurrentTeamCreditStop = ref({ stop_usd: 700 }) -const mockManageSubscription = vi.fn() -const mockShowSubscriptionDialog = vi.fn() -const mockResubscribe = vi.fn() const mockShowLeaveWorkspaceDialog = vi.fn() const mockShowCancelSubscriptionFlow = vi.fn() const mockShowEditWorkspaceDialog = vi.fn() @@ -174,33 +172,10 @@ const mockIsTeamPlan = computed( () => mockHasSubscription.value && mockHasTeamPlan.value ) -const mockInitialize = vi.fn() const mockIsLoading = ref(false) const mockError = ref(null) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - type: mockBillingType, - canAccessSubscriptionFeatures: computed( - () => mockIsActiveSubscription.value - ), - isFreeTier: computed(() => mockSubscriptionTier.value === 'FREE'), - billingStatus: mockBillingStatus, - subscriptionStatus: mockSubscriptionStatus, - isTeamPlan: mockIsTeamPlan, - subscription: mockSubscription, - plans: mockPlans, - teamCreditStops: mockTeamCreditStops, - currentTeamCreditStop: mockCurrentTeamCreditStop, - isLoading: mockIsLoading, - error: mockError, - showSubscriptionDialog: mockShowSubscriptionDialog, - manageSubscription: mockManageSubscription, - resubscribe: mockResubscribe, - initialize: mockInitialize, - getMaxSeats: () => 5 - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) const mockIsTeamPlanCancelled = computed( () => mockHasTeamPlan.value && (mockSubscription.value?.isCancelled ?? false) @@ -338,6 +313,25 @@ function renderComponent({ stubFooter = true } = {}) { describe('SubscriptionPanelContentWorkspace', () => { beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + type: computed(() => mockBillingType.value), + canAccessSubscriptionFeatures: computed( + () => mockIsActiveSubscription.value + ), + isFreeTier: computed(() => mockSubscriptionTier.value === 'FREE'), + billingStatus: computed(() => mockBillingStatus.value), + subscriptionStatus: computed(() => mockSubscriptionStatus.value), + isTeamPlan: mockIsTeamPlan, + subscription: mockSubscription, + plans: computed(() => mockPlans.value), + teamCreditStops: computed(() => mockTeamCreditStops.value), + currentTeamCreditStop: computed(() => mockCurrentTeamCreditStop.value), + isLoading: mockIsLoading, + error: mockError + } as const) + vi.mocked(useBillingContext().getMaxSeats).mockReturnValue(5) + mockDistributionState.isCloud = true mockSubscriptionStatus.value = 'active' mockBillingStatus.value = 'paid' @@ -675,10 +669,10 @@ describe('SubscriptionPanelContentWorkspace', () => { renderComponent() await user.click(screen.getByRole('button', { name: 'Billing & invoices' })) - expect(mockManageSubscription).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() await user.click(screen.getByRole('button', { name: 'Change plan' })) - expect(mockShowSubscriptionDialog).toHaveBeenCalledOnce() + expect(useBillingContext().showSubscriptionDialog).toHaveBeenCalledOnce() }) it('hides Change plan when the server denies seat changes to a client-side owner', () => { @@ -703,9 +697,9 @@ describe('SubscriptionPanelContentWorkspace', () => { screen.queryByRole('button', { name: 'Billing & invoices' }) ).not.toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Manage billing' })) - expect(mockManageSubscription).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() await user.click(screen.getByRole('button', { name: 'Invoice history' })) - expect(mockManageSubscription).toHaveBeenCalledTimes(2) + expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(2) }) it('keeps a Personal workspace Team-plan member view read-only', () => { @@ -766,7 +760,7 @@ describe('SubscriptionPanelContentWorkspace', () => { ).not.toBeInTheDocument() expect(screen.getByRole('heading', { name: 'Free' })).toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Billing & invoices' })) - expect(mockManageSubscription).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() expect( screen.getByRole('button', { name: 'Subscribe' }) ).toBeInTheDocument() @@ -848,8 +842,8 @@ describe('SubscriptionPanelContentWorkspace', () => { await user.click( screen.getByRole('button', { name: 'Resume subscription' }) ) - expect(mockResubscribe).toHaveBeenCalledOnce() - expect(mockShowSubscriptionDialog).not.toHaveBeenCalled() + expect(useBillingContext().resubscribe).toHaveBeenCalledOnce() + expect(useBillingContext().showSubscriptionDialog).not.toHaveBeenCalled() }) it('drops the state card for an inactive ended subscription without a date', () => { @@ -880,9 +874,9 @@ describe('SubscriptionPanelContentWorkspace', () => { screen.getByRole('heading', { name: 'Inactive team subscription' }) ).toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Billing & invoices' })) - expect(mockManageSubscription).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() await user.click(screen.getByRole('button', { name: 'Invoice history' })) - expect(mockManageSubscription).toHaveBeenCalledTimes(2) + expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(2) }) it('renders an ended Team plan for its owner and routes reactivation to checkout', async () => { @@ -936,10 +930,10 @@ describe('SubscriptionPanelContentWorkspace', () => { screen.getByRole('button', { name: 'Resume subscription' }) ) - expect(mockShowSubscriptionDialog).toHaveBeenCalledWith({ + expect(useBillingContext().showSubscriptionDialog).toHaveBeenCalledWith({ reason: 'settings_billing_panel' }) - expect(mockResubscribe).not.toHaveBeenCalled() + expect(useBillingContext().resubscribe).not.toHaveBeenCalled() }) it('keeps ended Team credits inactive when self-serve capabilities are unavailable', () => { @@ -1034,7 +1028,7 @@ describe('SubscriptionPanelContentWorkspace', () => { ) await user.click(screen.getByRole('button', { name: 'Billing & invoices' })) - expect(mockManageSubscription).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() }) it('lets a never-subscribed team workspace top up on Local instead of upselling', () => { @@ -1078,7 +1072,7 @@ describe('SubscriptionPanelContentWorkspace', () => { expect(screen.queryByText('Free')).not.toBeInTheDocument() await user.click(screen.getByRole('button', { name: 'Try again' })) - expect(mockInitialize).toHaveBeenCalledOnce() + expect(useBillingContext().initialize).toHaveBeenCalledOnce() }) it('hides Subscribe Now when the server denies self-serve to a client-side owner', () => { @@ -1142,10 +1136,10 @@ describe('SubscriptionPanelContentWorkspace', () => { ) await user.click(screen.getByRole('button', { name: 'Billing & invoices' })) - expect(mockManageSubscription).toHaveBeenCalledOnce() + expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() await user.click(screen.getByRole('button', { name: 'Subscribe' })) - expect(mockShowSubscriptionDialog).toHaveBeenCalledOnce() + expect(useBillingContext().showSubscriptionDialog).toHaveBeenCalledOnce() }) it.for([ diff --git a/src/platform/workspace/components/SubscriptionSuccessWorkspace.test.ts b/src/platform/workspace/components/SubscriptionSuccessWorkspace.test.ts index 8575285cf2c..cd996109e7c 100644 --- a/src/platform/workspace/components/SubscriptionSuccessWorkspace.test.ts +++ b/src/platform/workspace/components/SubscriptionSuccessWorkspace.test.ts @@ -1,3 +1,5 @@ +import { computed, ref } from 'vue' +import { useBillingContext } from '@/composables/billing/useBillingContext' import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -6,20 +8,11 @@ import { createI18n } from 'vue-i18n' import type { PreviewSubscribeResponse } from '@/platform/workspace/api/workspaceApi' import SubscriptionSuccessWorkspace from './SubscriptionSuccessWorkspace.vue' -const { mockInviteSubmit, mockMaxSeats, mockOccupiedSeats } = vi.hoisted( - () => ({ - mockInviteSubmit: vi.fn(), - mockMaxSeats: { value: 73 }, - mockOccupiedSeats: { value: 1 } - }) -) +const mockInviteSubmit = vi.hoisted(() => vi.fn()) +const mockMaxSeats = ref(73) +const mockOccupiedSeats = ref(1) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - maxSeats: mockMaxSeats, - occupiedSeats: mockOccupiedSeats - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('./InviteMembersForm.vue'), () => ({ default: { @@ -125,6 +118,12 @@ function renderTeamCard(props: Record = {}) { describe('SubscriptionSuccessWorkspace', () => { beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + maxSeats: computed(() => mockMaxSeats.value), + occupiedSeats: computed(() => mockOccupiedSeats.value) + } as const) + mockInviteSubmit.mockReset() mockMaxSeats.value = 73 mockOccupiedSeats.value = 1 diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index b577d79a165..231e4656a7b 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -4,6 +4,7 @@ import { setPersistence } from 'firebase/auth' +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { @@ -30,16 +31,11 @@ import type { BillingOperation } from '@/platform/workspace/composables/billingO import TopUpCreditsDialogContentWorkspace from './TopUpCreditsDialogContentWorkspace.vue' -const mockFetchBalance = vi.fn() -const mockFetchStatus = vi.fn() -const mockManageSubscription = vi.fn<() => Promise>() const mockReportError = vi.hoisted(() => vi.fn()) vi.mock(import('@/platform/telemetry/reportError'), () => ({ reportError: mockReportError })) -const mockTopup = - vi.fn<(amountCents: number) => Promise>() const mockShowSettings = vi.fn() const mockToastAdd = vi.fn() @@ -68,14 +64,7 @@ vi.mock( } ) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - fetchBalance: mockFetchBalance, - fetchStatus: mockFetchStatus, - manageSubscription: mockManageSubscription, - topup: (amountCents: number) => mockTopup(amountCents) - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('@/platform/workspace/composables/useBillingCapabilities'), @@ -225,8 +214,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { setCanTopUp(true) setIsAddingCredits(false) setTopupActionOperation(undefined) - mockFetchBalance.mockResolvedValue(undefined) - mockFetchStatus.mockResolvedValue(undefined) + setHasSavedPaymentMethod(true) vi.mocked(useBillingOperationStore().startOperation).mockImplementation( () => { @@ -237,7 +225,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('fires a started event before the purchase resolves', async () => { - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(useBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) renderDialog() await clickAddCredits() @@ -336,8 +326,6 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('reports failure telemetry when topup resolves with no response', async () => { - mockTopup.mockResolvedValue(undefined) - renderDialog() await clickAddCredits() await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) @@ -368,7 +356,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(screen.getByText('Total due today')).toBeInTheDocument() expect(screen.getByText('$50.00')).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Pay $50.00' })).toBeEnabled() - expect(mockTopup).not.toHaveBeenCalled() + expect(useBillingContext().topup).not.toHaveBeenCalled() }) it('shows the saved-card note when a payment method is on file', async () => { @@ -398,7 +386,6 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('opens the billing portal from the no-payment-method note', async () => { setHasSavedPaymentMethod(false) - mockManageSubscription.mockResolvedValue(undefined) renderDialog() await clickAddCredits() @@ -407,13 +394,13 @@ describe('TopUpCreditsDialogContentWorkspace', () => { await screen.findByRole('button', { name: 'Manage billing' }) ) - expect(mockManageSubscription).toHaveBeenCalledTimes(1) + expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(1) }) it('reports and surfaces a billing-portal opening failure', async () => { setHasSavedPaymentMethod(false) const failure = new Error('portal down') - mockManageSubscription.mockRejectedValue(failure) + vi.mocked(useBillingContext().manageSubscription).mockRejectedValue(failure) renderDialog() await clickAddCredits() @@ -436,7 +423,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('explains how to add a payment method when the purchase is refused', async () => { setHasSavedPaymentMethod(false) - mockTopup.mockRejectedValue( + vi.mocked(useBillingContext().topup).mockRejectedValue( new WorkspaceApiError( 'No default payment method is selected.', 400, @@ -704,7 +691,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('locks pending payment actions and prevents duplicate top-ups', async () => { - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(useBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) renderDialog() await clickAddCredits() @@ -724,12 +713,14 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ) payButton.dispatchEvent(new MouseEvent('click', { bubbles: true })) - expect(mockTopup).toHaveBeenCalledOnce() + expect(useBillingContext().topup).toHaveBeenCalledOnce() }) it('unlocks payment and reports an operation start failure', async () => { const error = new Error('Operation unavailable') - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(useBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) vi.mocked(useBillingOperationStore().startOperation).mockRejectedValue( error ) @@ -760,14 +751,16 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('refreshes both balance and status after a completed top-up', async () => { - mockTopup.mockResolvedValue(topupResponse('completed')) + vi.mocked(useBillingContext().topup).mockResolvedValue( + topupResponse('completed') + ) renderDialog() await clickAddCredits() await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) - expect(mockFetchBalance).toHaveBeenCalledOnce() - expect(mockFetchStatus).toHaveBeenCalledOnce() + expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce() + expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(mockShowSettings).toHaveBeenCalledWith('workspace') expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'topup', @@ -797,7 +790,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('opens Credits settings after a completed local top-up', async () => { mockDistributionTypes.isCloud = false - mockTopup.mockResolvedValue(topupResponse('completed')) + vi.mocked(useBillingContext().topup).mockResolvedValue( + topupResponse('completed') + ) renderDialog() await clickAddCredits() @@ -807,9 +802,15 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('keeps completed top-up telemetry successful when refresh fails', async () => { - mockTopup.mockResolvedValue(topupResponse('completed')) - mockFetchBalance.mockRejectedValueOnce(new Error('balance unavailable')) - mockFetchStatus.mockRejectedValueOnce(new Error('status unavailable')) + vi.mocked(useBillingContext().topup).mockResolvedValue( + topupResponse('completed') + ) + vi.mocked(useBillingContext().fetchBalance).mockRejectedValueOnce( + new Error('balance unavailable') + ) + vi.mocked(useBillingContext().fetchStatus).mockRejectedValueOnce( + new Error('status unavailable') + ) renderDialog() await clickAddCredits() @@ -827,7 +828,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('does not refresh balance or status for a pending top-up', async () => { - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(useBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) renderDialog() await clickAddCredits() @@ -841,22 +844,24 @@ describe('TopUpCreditsDialogContentWorkspace', () => { autoHandleRequiresAction: true } ) - expect(mockFetchBalance).not.toHaveBeenCalled() - expect(mockFetchStatus).not.toHaveBeenCalled() + expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() + expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() expect(useTelemetry()?.trackBillingEvent).not.toHaveBeenCalledWith( expect.objectContaining({ stage: 'succeeded' }) ) }) it('does not refresh balance or status for a failed top-up', async () => { - mockTopup.mockResolvedValue(topupResponse('failed')) + vi.mocked(useBillingContext().topup).mockResolvedValue( + topupResponse('failed') + ) renderDialog() await clickAddCredits() await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) - expect(mockFetchBalance).not.toHaveBeenCalled() - expect(mockFetchStatus).not.toHaveBeenCalled() + expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() + expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'topup', stage: 'failed', @@ -878,7 +883,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('categorizes a thrown topup error via the shared classifier', async () => { const workspaceApiError = new WorkspaceApiError('upstream rejected', 500) - mockTopup.mockRejectedValue(workspaceApiError) + vi.mocked(useBillingContext().topup).mockRejectedValue(workspaceApiError) renderDialog() await clickAddCredits() @@ -903,7 +908,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(screen.getByRole('button', { name: 'Pay $50.00' })).toBeDisabled() - expect(mockTopup).not.toHaveBeenCalled() + expect(useBillingContext().topup).not.toHaveBeenCalled() expect( useTelemetry()?.trackApiCreditTopupButtonPurchaseClicked ).not.toHaveBeenCalled() diff --git a/src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts b/src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts index 8029b40d6d4..60d7f3d553f 100644 --- a/src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts +++ b/src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts @@ -1,3 +1,5 @@ +import { computed, ref } from 'vue' +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useDialogStore } from '@/stores/dialogStore' import { render, screen, waitFor } from '@testing-library/vue' @@ -11,24 +13,11 @@ import InviteMemberDialogContent from './InviteMemberDialogContent.vue' import type { WorkspacePendingInvite } from '@/platform/workspace/stores/teamWorkspaceStore' -const { mockToastAdd, mockFetchStatus, mockMaxSeats, mockOccupiedSeats } = - vi.hoisted(() => { - const nullableNumber = (value: number | null) => ({ value }) - return { - mockToastAdd: vi.fn(), - mockFetchStatus: vi.fn(), - mockMaxSeats: nullableNumber(73), - mockOccupiedSeats: nullableNumber(0) - } - }) +const mockToastAdd = vi.hoisted(() => vi.fn()) +const mockMaxSeats = ref(73) +const mockOccupiedSeats = ref(0) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - fetchStatus: mockFetchStatus, - maxSeats: mockMaxSeats, - occupiedSeats: mockOccupiedSeats - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('@/platform/telemetry')) @@ -75,6 +64,12 @@ function inviteButton() { } beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + maxSeats: computed(() => mockMaxSeats.value), + occupiedSeats: computed(() => mockOccupiedSeats.value) + } as const) + Object.assign(useTeamWorkspaceStore(), { pendingInvites: [] }) vi.mocked(useDialogStore().closeDialog).mockImplementation(() => {}) }) @@ -83,7 +78,7 @@ describe('InviteMemberDialogContent', () => { beforeEach(() => { vi.useRealTimers() vi.mocked(useTeamWorkspaceStore().fetchPendingInvites).mockResolvedValue([]) - mockFetchStatus.mockResolvedValue(undefined) + vi.mocked(useBillingContext().fetchStatus).mockResolvedValue(undefined) mockMaxSeats.value = 73 mockOccupiedSeats.value = 0 vi.mocked(useTeamWorkspaceStore().createInvite).mockImplementation( diff --git a/src/platform/workspace/composables/useResubscribe.test.ts b/src/platform/workspace/composables/useResubscribe.test.ts index e092a26e264..fb21b97ae88 100644 --- a/src/platform/workspace/composables/useResubscribe.test.ts +++ b/src/platform/workspace/composables/useResubscribe.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createApp, defineComponent } from 'vue' import type { App } from 'vue' @@ -14,13 +15,10 @@ const state = vi.hoisted(() => ({ canManageSubscriptionLifecycle: true, canReactivate: true, canReactivatePlan: true, - resubscribe: vi.fn(), toastAdd: vi.fn() })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ resubscribe: state.resubscribe }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('@/composables/billing/useBillingRouting'), () => ({ useBillingRouting: () => ({ @@ -105,7 +103,6 @@ describe('useResubscribe', () => { state.canManageSubscriptionLifecycle = true state.canReactivate = true state.canReactivatePlan = true - state.resubscribe.mockResolvedValue(undefined) }) it('does not resubscribe after the workspace role loses permission', async () => { @@ -116,7 +113,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).not.toHaveBeenCalled() + expect(useBillingContext().resubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackResubscribeClicked).not.toHaveBeenCalled() expect(state.toastAdd).not.toHaveBeenCalled() expect(isResubscribing.value).toBe(false) @@ -130,7 +127,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).not.toHaveBeenCalled() + expect(useBillingContext().resubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackResubscribeClicked).not.toHaveBeenCalled() expect(state.toastAdd).not.toHaveBeenCalled() expect(isResubscribing.value).toBe(false) @@ -146,7 +143,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).toHaveBeenCalled() + expect(useBillingContext().resubscribe).toHaveBeenCalled() }) it('refuses whenever the policy denies it', async () => { @@ -158,7 +155,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).not.toHaveBeenCalled() + expect(useBillingContext().resubscribe).not.toHaveBeenCalled() }) it('fires a started event before resubscribe resolves', async () => { @@ -184,7 +181,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).toHaveBeenCalledOnce() + expect(useBillingContext().resubscribe).toHaveBeenCalledOnce() expect(useTelemetry()?.trackResubscribeClicked).toHaveBeenCalledOnce() expect(useTelemetry()?.trackBillingEvent).not.toHaveBeenCalledWith( expect.objectContaining({ stage: 'succeeded' }) @@ -204,14 +201,14 @@ describe('useResubscribe', () => { }) it('shows an error and resets loading when resubscription fails', async () => { - state.resubscribe.mockRejectedValueOnce( + vi.mocked(useBillingContext().resubscribe).mockRejectedValueOnce( new Error('Resubscribe failed for person@example.com') ) const { handleResubscribe, isResubscribing } = useResubscribe() await handleResubscribe() - expect(state.resubscribe).toHaveBeenCalledOnce() + expect(useBillingContext().resubscribe).toHaveBeenCalledOnce() expect(state.toastAdd).toHaveBeenCalledWith( expect.objectContaining({ severity: 'error', @@ -234,7 +231,9 @@ describe('useResubscribe', () => { 'checkout initiation rejected', 500 ) - state.resubscribe.mockRejectedValueOnce(authStoreError) + vi.mocked(useBillingContext().resubscribe).mockRejectedValueOnce( + authStoreError + ) const { handleResubscribe } = useResubscribe() await handleResubscribe() @@ -254,7 +253,9 @@ describe('useResubscribe', () => { it('categorizes an AuthStoreError with no status as a network failure, not an api rejection', async () => { state.shouldUseWorkspaceBilling = false const authStoreError = new AuthStoreError('offline') - state.resubscribe.mockRejectedValueOnce(authStoreError) + vi.mocked(useBillingContext().resubscribe).mockRejectedValueOnce( + authStoreError + ) const { handleResubscribe } = useResubscribe() await handleResubscribe() @@ -270,7 +271,7 @@ describe('useResubscribe', () => { it('emits started before the awaited resubscribe call resolves', async () => { const callOrder: string[] = [] - state.resubscribe.mockImplementation(async () => { + vi.mocked(useBillingContext().resubscribe).mockImplementation(async () => { callOrder.push('resubscribe') }) vi.mocked(useTelemetry()?.trackBillingEvent)?.mockImplementation( diff --git a/src/platform/workspace/stores/billingOperationStore.test.ts b/src/platform/workspace/stores/billingOperationStore.test.ts index 156378e70c2..e5667d4194d 100644 --- a/src/platform/workspace/stores/billingOperationStore.test.ts +++ b/src/platform/workspace/stores/billingOperationStore.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { bindOperationToCheckoutJourney, @@ -25,21 +26,12 @@ vi.mock(import('@stripe/stripe-js/pure'), () => ({ loadStripe: mockLoadStripe })) -const mockFetchStatus = vi.fn() -const mockFetchBalance = vi.fn() -const mockReconcileSubscriptionSuccess = vi.fn() const mockRefreshCapabilities = vi.fn() const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true })) vi.mock(import('@/platform/distribution/types'), () => mockDistributionTypes) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - fetchStatus: mockFetchStatus, - fetchBalance: mockFetchBalance, - reconcileSubscriptionSuccess: mockReconcileSubscriptionSuccess - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('@/platform/workspace/composables/useBillingCapabilities'), @@ -475,9 +467,11 @@ describe('billingOperationStore', () => { expect(store.hasPendingOperations).toBe(false) expect(mockRefreshCapabilities).toHaveBeenCalledOnce() - expect(mockReconcileSubscriptionSuccess).toHaveBeenCalledOnce() - expect(mockFetchStatus).not.toHaveBeenCalled() - expect(mockFetchBalance).not.toHaveBeenCalled() + expect( + useBillingContext().reconcileSubscriptionSuccess + ).toHaveBeenCalledOnce() + expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() + expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() expect(useToastStore().add).toHaveBeenCalledWith({ severity: 'success', @@ -891,7 +885,9 @@ describe('billingOperationStore', () => { status: 'succeeded', started_at: new Date().toISOString() }) - mockReconcileSubscriptionSuccess.mockImplementationOnce(() => { + vi.mocked( + useBillingContext().reconcileSubscriptionSuccess + ).mockImplementationOnce(() => { throw new Error('reconcile failed') }) @@ -2473,7 +2469,7 @@ describe('billingOperationStore', () => { const operation = await terminal expect(operation.status).toBe('succeeded') - expect(mockFetchStatus).toHaveBeenCalled() + expect(useBillingContext().fetchStatus).toHaveBeenCalled() expect( useTeamWorkspaceStore().updateActiveWorkspace ).toHaveBeenCalledWith({ @@ -2490,7 +2486,9 @@ describe('billingOperationStore', () => { }) it('resolves the terminal outcome even when the post-success refresh fails', async () => { - mockFetchStatus.mockRejectedValueOnce(new Error('refresh failed')) + vi.mocked(useBillingContext().fetchStatus).mockRejectedValueOnce( + new Error('refresh failed') + ) vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', diff --git a/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts b/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts index 669e34ff6a9..b7f8170dc4d 100644 --- a/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts +++ b/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts @@ -1,3 +1,4 @@ +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useExecutionStore } from '@/stores/executionStore' import { useExecutionErrorStore } from '@/stores/executionErrorStore' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' @@ -7,7 +8,7 @@ import { useOnboardingTourStore } from '@/platform/onboarding/onboardingTourStor import { fromPartial } from '@total-typescript/shoehorn' import type { DetachedWindowAPI } from 'happy-dom' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { effectScope, nextTick, ref } from 'vue' +import { effectScope, nextTick, ref, computed } from 'vue' import type { EffectScope, Ref } from 'vue' import type { TourEnding } from '@/platform/onboarding/onboardingTourStore' @@ -31,7 +32,6 @@ const ACCEPT_DEADLINE_MS = 15_000 const mocks = vi.hoisted(() => { return { canRunWorkflows: { value: true }, - showSubscriptionDialog: vi.fn(), workflowStatus: { value: new Map() }, steps: [] as CoachStep[], @@ -40,12 +40,7 @@ const mocks = vi.hoisted(() => { } }) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - canRunWorkflows: mocks.canRunWorkflows, - showSubscriptionDialog: mocks.showSubscriptionDialog - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('./firstRunTourDefinition'), () => ({ firstRunTourSteps: (_templateId: string, runState: Ref) => { @@ -178,6 +173,11 @@ function mountRunButton( } beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + canRunWorkflows: computed(() => mocks.canRunWorkflows.value) + } as const) + Object.assign(useOnboardingTourStore(), { activeTour: ref['activeTour']>(null), @@ -995,7 +995,7 @@ describe('useFirstRunTourController', () => { 'the subscribe button opens the paywall itself, with its own reason and telemetry' ).toHaveBeenCalled() expect( - mocks.showSubscriptionDialog, + useBillingContext().showSubscriptionDialog, 'opening it here too would replace the button reason with the tour own' ).not.toHaveBeenCalled() expect( diff --git a/src/renderer/extensions/linearMode/LinearControls.test.ts b/src/renderer/extensions/linearMode/LinearControls.test.ts index 5653d2f5382..6a895e16716 100644 --- a/src/renderer/extensions/linearMode/LinearControls.test.ts +++ b/src/renderer/extensions/linearMode/LinearControls.test.ts @@ -1,9 +1,10 @@ import { getActivePinia } from 'pinia' import { render, screen, within } from '@testing-library/vue' -import { nextTick } from 'vue' +import { computed, nextTick } from 'vue' import { createI18n } from 'vue-i18n' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { useBillingContext } from '@/composables/billing/useBillingContext' import { useMissingMediaStore } from '@/platform/missingMedia/missingMediaStore' import type { MissingMediaCandidate } from '@/platform/missingMedia/types' import { useMissingModelStore } from '@/platform/missingModel/missingModelStore' @@ -16,20 +17,12 @@ import { useAppModeStore } from '@/stores/appModeStore' import { useExecutionErrorStore } from '@/stores/executionErrorStore' import { toNodeId } from '@/types/nodeId' -const billingMock = vi.hoisted(() => ({ - canRunWorkflows: true -})) - const overlayMock = vi.hoisted(() => ({ overlayMessage: 'KSampler is missing a required input: model', overlayTitle: 'Required input missing' })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - canRunWorkflows: billingMock.canRunWorkflows - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock(import('@/components/error/useErrorOverlayState'), () => ({ useErrorOverlayState: () => ({ @@ -111,7 +104,10 @@ function renderControls({ canRunWorkflows?: boolean mobile?: boolean } = {}) { - billingMock.canRunWorkflows = canRunWorkflows + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + canRunWorkflows: computed(() => canRunWorkflows) + } as const) const pinia = getActivePinia()! @@ -163,7 +159,6 @@ function clearMissingResource(resource: MissingResource) { describe('LinearControls', () => { beforeEach(() => { - billingMock.canRunWorkflows = true overlayMock.overlayMessage = 'KSampler is missing a required input: model' overlayMock.overlayTitle = 'Required input missing' }) diff --git a/src/services/dialogService.downgrade.test.ts b/src/services/dialogService.downgrade.test.ts index 512c33fa441..8a47dccfa0a 100644 --- a/src/services/dialogService.downgrade.test.ts +++ b/src/services/dialogService.downgrade.test.ts @@ -1,3 +1,5 @@ +import { computed } from 'vue' +import { useBillingContext } from '@/composables/billing/useBillingContext' import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import type { Component } from 'vue' import type DowngradeContent from '@/platform/workspace/components/dialogs/DowngradeRemoveMembersDialogContent.vue' @@ -40,17 +42,20 @@ vi.mock(import('@/i18n'), () => ({ vi.mock(import('@/platform/telemetry')) +beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + canAccessSubscriptionFeatures: computed(() => true), + isFreeTier: computed(() => false), + type: computed(() => 'legacy') + } as const) +}) + vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: false })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - canAccessSubscriptionFeatures: { value: true }, - isFreeTier: { value: false }, - type: { value: 'legacy' } - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('@/platform/workspace/composables/useDowngradeToPersonal'), diff --git a/src/services/dialogService.renderer.test.ts b/src/services/dialogService.renderer.test.ts index d0b7d7f9f55..dbf67e8b703 100644 --- a/src/services/dialogService.renderer.test.ts +++ b/src/services/dialogService.renderer.test.ts @@ -1,3 +1,5 @@ +import { computed } from 'vue' +import { useBillingContext } from '@/composables/billing/useBillingContext' /** * Dialog migration regression net: when callers in `dialogService` open a * Reka-migrated dialog, the dialog stack item must carry `renderer: 'reka'`. @@ -11,18 +13,21 @@ vi.mock(import('@/i18n'), () => ({ vi.mock(import('@/platform/telemetry')) +beforeEach(() => { + vi.mocked(useBillingContext).mockReturnValue({ + ...useBillingContext(), + canAccessSubscriptionFeatures: computed(() => true), + isTeamPlan: computed(() => false), + tier: computed(() => 'STANDARD'), + type: computed(() => 'legacy') + } as const) +}) + vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: false })) -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => ({ - canAccessSubscriptionFeatures: { value: true }, - isTeamPlan: { value: false }, - tier: { value: 'STANDARD' }, - type: { value: 'legacy' } - }) -})) +vi.mock(import('@/composables/billing/useBillingContext')) vi.mock( import('@/platform/workspace/composables/useBillingCapabilities'), From c1d0b92e5cac8a11846ce1271542864351de16a6 Mon Sep 17 00:00:00 2001 From: Amp Date: Tue, 15 Sep 2026 03:10:46 +0000 Subject: [PATCH 2/4] test: simplify billing context mock setup Amp-Thread-ID: https://ampcode.com/threads/T-01a0a2f9-a153-7099-9a4a-1dc942db28ca --- .../content/setting/CreditsPanel.test.ts | 19 ++--- .../topbar/CurrentUserPopoverLegacy.test.ts | 7 +- .../billing/__mocks__/useBillingContext.ts | 17 +++-- .../components/FreeTierQuota.test.ts | 7 +- .../components/SubscribeToRun.test.ts | 2 + .../SubscriptionFooterLinks.test.ts | 2 + .../useAccountPreconditionDialog.test.ts | 12 ++- .../usePaymentReturnUrlLoader.test.ts | 12 ++- .../usePricingTableUrlLoader.test.ts | 9 +-- .../useSubscriptionActions.test.ts | 10 ++- .../composables/useSettingsDialog.test.ts | 7 +- .../components/InviteMembersForm.test.ts | 6 +- .../components/PricingTableWorkspace.test.ts | 9 +-- .../SubscriptionPanelContentWorkspace.test.ts | 9 ++- .../SubscriptionSuccessWorkspace.test.ts | 7 +- ...TopUpCreditsDialogContentWorkspace.test.ts | 74 +++++++++++-------- .../dialogs/InviteMemberDialogContent.test.ts | 7 +- .../composables/useResubscribe.test.ts | 27 ++++--- .../stores/billingOperationStore.test.ts | 30 +++++--- .../tour/useFirstRunTourController.test.ts | 7 +- .../linearMode/LinearControls.test.ts | 7 +- src/services/dialogService.downgrade.test.ts | 7 +- src/services/dialogService.renderer.test.ts | 9 ++- 23 files changed, 176 insertions(+), 127 deletions(-) diff --git a/src/components/dialog/content/setting/CreditsPanel.test.ts b/src/components/dialog/content/setting/CreditsPanel.test.ts index 704ee2e89f6..7f31e3c4ac4 100644 --- a/src/components/dialog/content/setting/CreditsPanel.test.ts +++ b/src/components/dialog/content/setting/CreditsPanel.test.ts @@ -1,6 +1,6 @@ import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/vue' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { computed, defineComponent, h, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' @@ -9,7 +9,6 @@ import { useBillingContext } from '@/composables/billing/useBillingContext' import CreditsPanel from './CreditsPanel.vue' -const balance = ref(null) vi.mock(import('@/composables/billing/useBillingContext')) const refreshActivity = vi.hoisted(() => vi.fn()) @@ -69,14 +68,6 @@ function makeBalance(amountMicros: number): BalanceInfo { } describe('CreditsPanel', () => { - beforeEach(() => { - balance.value = null - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), - balance: computed(() => balance.value) - } as const) - }) - function renderComponent() { return render(CreditsPanel, { global: { plugins: [i18n], stubs: { Divider: true } } @@ -84,15 +75,21 @@ describe('CreditsPanel', () => { } it('opens the billing portal for the active billing rail', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) const user = userEvent.setup() renderComponent() await user.click(screen.getByRole('button', { name: /Invoice History/ })) - expect(useBillingContext().manageSubscription).toHaveBeenCalledOnce() + expect(billing.manageSubscription).toHaveBeenCalledOnce() }) it('refreshes activity on a balance change but not on first hydration', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) + const balance = ref(null) + billing.balance = computed(() => balance.value) renderComponent() balance.value = makeBalance(5000) diff --git a/src/components/topbar/CurrentUserPopoverLegacy.test.ts b/src/components/topbar/CurrentUserPopoverLegacy.test.ts index b90dcd96baa..f0689d698cf 100644 --- a/src/components/topbar/CurrentUserPopoverLegacy.test.ts +++ b/src/components/topbar/CurrentUserPopoverLegacy.test.ts @@ -26,8 +26,8 @@ vi.mock(import('@/platform/settings/composables/useSettingsDialog'), () => ({ const originalWindowOpen = window.open beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), + const billing = useBillingContext() + Object.assign(billing, { canAccessSubscriptionFeatures: computed( () => mockCanAccessSubscriptionFeatures.value ), @@ -36,7 +36,8 @@ beforeEach(() => { balance: computed(() => mockBalance.value), isLoading: mockIsLoading, isTeamPlan: computed(() => mockIsTeamPlan.value) - } as const) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) window.open = vi.fn() }) diff --git a/src/composables/billing/__mocks__/useBillingContext.ts b/src/composables/billing/__mocks__/useBillingContext.ts index 403884dd13b..43732800d82 100644 --- a/src/composables/billing/__mocks__/useBillingContext.ts +++ b/src/composables/billing/__mocks__/useBillingContext.ts @@ -1,12 +1,11 @@ -import { beforeEach, vi } from 'vitest' +import { vi } from 'vitest' import { computed, ref } from 'vue' +import type { BillingContext } from '../types' import type { useBillingContext as realUseBillingContext } from '../useBillingContext' -export const useBillingContext = vi.fn() - -beforeEach(() => { - useBillingContext.mockReturnValue({ +function createBillingContextMock(): BillingContext { + return { type: computed(() => 'legacy'), isInitialized: ref(false), isLoading: ref(false), @@ -43,5 +42,9 @@ beforeEach(() => { requireActiveSubscription: vi.fn(async () => {}), showSubscriptionDialog: vi.fn(), reconcileSubscriptionSuccess: vi.fn(async () => {}) - } as const) -}) + } +} + +export const useBillingContext = vi.fn( + createBillingContextMock +) diff --git a/src/platform/cloud/subscription/components/FreeTierQuota.test.ts b/src/platform/cloud/subscription/components/FreeTierQuota.test.ts index 903d0ee9ccc..b791b4b0b48 100644 --- a/src/platform/cloud/subscription/components/FreeTierQuota.test.ts +++ b/src/platform/cloud/subscription/components/FreeTierQuota.test.ts @@ -37,10 +37,9 @@ const i18n = createI18n({ describe('FreeTierQuota', () => { beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), - isFreeTier: computed(() => mockIsFreeTier.value) - } as const) + const billing = useBillingContext() + billing.isFreeTier = computed(() => mockIsFreeTier.value) + vi.mocked(useBillingContext).mockReturnValue(billing) mockIsFreeTier.value = true mockAvailable.value = 3 diff --git a/src/platform/cloud/subscription/components/SubscribeToRun.test.ts b/src/platform/cloud/subscription/components/SubscribeToRun.test.ts index bd3301e5b00..1ba2cb1895a 100644 --- a/src/platform/cloud/subscription/components/SubscribeToRun.test.ts +++ b/src/platform/cloud/subscription/components/SubscribeToRun.test.ts @@ -59,6 +59,8 @@ const i18n = createI18n({ }) function renderButton() { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) const user = userEvent.setup() const result = render(SubscribeToRun, { global: { diff --git a/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts b/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts index 2e6cf10ba21..f9f71276f8b 100644 --- a/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts +++ b/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts @@ -62,6 +62,8 @@ const i18n = createI18n({ function renderComponent( props: Partial> = {} ) { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) return render(SubscriptionFooterLinks, { props, global: { diff --git a/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts b/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts index 0b5830684d7..9bf5659864d 100644 --- a/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts +++ b/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts @@ -57,16 +57,20 @@ describe('useAccountPreconditionDialog', () => { }) it('refreshes the billing snapshot on a credit precondition so exhausted-state surfaces converge', () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) useAccountPreconditionDialog().open('credits') - expect(useBillingContext().fetchStatus).toHaveBeenCalledTimes(1) - expect(useBillingContext().fetchBalance).toHaveBeenCalledTimes(1) + expect(billing.fetchStatus).toHaveBeenCalledTimes(1) + expect(billing.fetchBalance).toHaveBeenCalledTimes(1) }) it('does not touch billing state for non-credit preconditions', () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) useAccountPreconditionDialog().open('subscription') - expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() - expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() + expect(billing.fetchStatus).not.toHaveBeenCalled() + expect(billing.fetchBalance).not.toHaveBeenCalled() }) }) diff --git a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts index 9ba49a55844..390aa1365a4 100644 --- a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts +++ b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts @@ -28,6 +28,8 @@ describe('usePaymentReturnUrlLoader', () => { }) it('refreshes billing after bootstrap strips Stripe return params', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) window.history.replaceState( {}, '', @@ -39,19 +41,23 @@ describe('usePaymentReturnUrlLoader', () => { await loadPaymentReturnFromUrl() expect(window.location.search).toBe('?workspace=ws-1') - expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() + expect(billing.fetchStatus).toHaveBeenCalledOnce() }) it('does nothing on an ordinary page load', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) window.history.replaceState({}, '', '/?workspace=ws-1') const { loadPaymentReturnFromUrl } = usePaymentReturnUrlLoader() await loadPaymentReturnFromUrl() - expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() + expect(billing.fetchStatus).not.toHaveBeenCalled() }) it('does not start embedded recovery while the flag is off', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) mocks.embeddedCheckoutEnabled = false window.history.replaceState( {}, @@ -62,6 +68,6 @@ describe('usePaymentReturnUrlLoader', () => { await usePaymentReturnUrlLoader().loadPaymentReturnFromUrl() - expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() + expect(billing.fetchStatus).not.toHaveBeenCalled() }) }) diff --git a/src/platform/cloud/subscription/composables/usePricingTableUrlLoader.test.ts b/src/platform/cloud/subscription/composables/usePricingTableUrlLoader.test.ts index 7d1c4ff7549..32cfa078dac 100644 --- a/src/platform/cloud/subscription/composables/usePricingTableUrlLoader.test.ts +++ b/src/platform/cloud/subscription/composables/usePricingTableUrlLoader.test.ts @@ -92,10 +92,9 @@ const TEAM_CREDIT_STOPS = { describe('usePricingTableUrlLoader', () => { beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), - teamCreditStops: computed(() => mockTeamCreditStops.value) - } as const) + const billing = useBillingContext() + billing.teamCreditStops = computed(() => mockTeamCreditStops.value) + vi.mocked(useBillingContext).mockReturnValue(billing) mockRouteQuery.value = {} mockPermissions.value = { canManageSubscription: true } @@ -103,7 +102,7 @@ describe('usePricingTableUrlLoader', () => { mockInitializeCapabilities.mockClear() mockInitializeCapabilities.mockResolvedValue(undefined) mockTeamCreditStops.value = TEAM_CREDIT_STOPS - vi.mocked(useBillingContext().fetchPlans).mockResolvedValue(undefined) + vi.mocked(billing.fetchPlans).mockResolvedValue(undefined) mockShowPricingTable.mockResolvedValue(undefined) preservedQueryMocks.mergePreservedQueryIntoQuery.mockReturnValue(null) }) diff --git a/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts b/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts index c1869ad65ad..a6dd775baf6 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts @@ -161,16 +161,20 @@ describe('useSubscriptionActions', () => { describe('handleRefresh', () => { it('should refresh balance and status through the billing facade', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) const { handleRefresh } = useSubscriptionActions() await handleRefresh() - expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce() - expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() + expect(billing.fetchBalance).toHaveBeenCalledOnce() + expect(billing.fetchStatus).toHaveBeenCalledOnce() expect(useAuthActions().fetchBalance).not.toHaveBeenCalled() }) it('swallows refresh failures without surfacing a toast', async () => { - vi.mocked(useBillingContext().fetchBalance).mockRejectedValueOnce( + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) + vi.mocked(billing.fetchBalance).mockRejectedValueOnce( new Error('Fetch failed') ) const { handleRefresh } = useSubscriptionActions() diff --git a/src/platform/settings/composables/useSettingsDialog.test.ts b/src/platform/settings/composables/useSettingsDialog.test.ts index 514aea1987a..9480cbd06ba 100644 --- a/src/platform/settings/composables/useSettingsDialog.test.ts +++ b/src/platform/settings/composables/useSettingsDialog.test.ts @@ -25,12 +25,13 @@ vi.mock(import('@/i18n'), () => ({ vi.mock(import('@/platform/telemetry')) beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), + const billing = useBillingContext() + Object.assign(billing, { canAccessSubscriptionFeatures: computed(() => true), isFreeTier: computed(() => false), type: computed(() => 'legacy') - } as const) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) }) vi.mock(import('@/composables/billing/useBillingContext')) diff --git a/src/platform/workspace/components/InviteMembersForm.test.ts b/src/platform/workspace/components/InviteMembersForm.test.ts index 59b45cd75d4..3ad2215e203 100644 --- a/src/platform/workspace/components/InviteMembersForm.test.ts +++ b/src/platform/workspace/components/InviteMembersForm.test.ts @@ -46,6 +46,8 @@ function pendingInviteFor(email: string): WorkspacePendingInvite { } function renderForm(props: Record = {}) { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) const user = userEvent.setup() const result = render(InviteMembersForm, { props: { @@ -127,11 +129,11 @@ describe('InviteMembersForm', () => { it('completes submission when the billing refresh fails', async () => { const refreshError = new Error('refresh failed') + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { user, emitted } = renderForm() vi.mocked(useBillingContext().fetchStatus).mockRejectedValueOnce( refreshError ) - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) - const { user, emitted } = renderForm() await user.type(emailInput(), 'a@b.com{Enter}') await user.click(submitButton()) diff --git a/src/platform/workspace/components/PricingTableWorkspace.test.ts b/src/platform/workspace/components/PricingTableWorkspace.test.ts index 945cce95119..a0e25cbf3ba 100644 --- a/src/platform/workspace/components/PricingTableWorkspace.test.ts +++ b/src/platform/workspace/components/PricingTableWorkspace.test.ts @@ -72,12 +72,11 @@ beforeEach(() => { describe('PricingTableWorkspace credit allotment copy', () => { beforeEach(() => { + const billing = useBillingContext() state.plans = [] - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), - plans: computed(() => state.plans) - } as const) - vi.mocked(useBillingContext().getMaxSeats).mockReturnValue(5) + billing.plans = computed(() => state.plans) + vi.mocked(billing.getMaxSeats).mockReturnValue(5) + vi.mocked(useBillingContext).mockReturnValue(billing) }) it('shows the catalog grant in preference to twelve static months', () => { diff --git a/src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts b/src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts index 6d6a377288d..bd74c8a5d41 100644 --- a/src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts +++ b/src/platform/workspace/components/SubscriptionPanelContentWorkspace.test.ts @@ -313,8 +313,8 @@ function renderComponent({ stubFooter = true } = {}) { describe('SubscriptionPanelContentWorkspace', () => { beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), + const billing = useBillingContext() + Object.assign(billing, { type: computed(() => mockBillingType.value), canAccessSubscriptionFeatures: computed( () => mockIsActiveSubscription.value @@ -329,8 +329,9 @@ describe('SubscriptionPanelContentWorkspace', () => { currentTeamCreditStop: computed(() => mockCurrentTeamCreditStop.value), isLoading: mockIsLoading, error: mockError - } as const) - vi.mocked(useBillingContext().getMaxSeats).mockReturnValue(5) + }) + vi.mocked(billing.getMaxSeats).mockReturnValue(5) + vi.mocked(useBillingContext).mockReturnValue(billing) mockDistributionState.isCloud = true mockSubscriptionStatus.value = 'active' diff --git a/src/platform/workspace/components/SubscriptionSuccessWorkspace.test.ts b/src/platform/workspace/components/SubscriptionSuccessWorkspace.test.ts index cd996109e7c..54d9334ce1a 100644 --- a/src/platform/workspace/components/SubscriptionSuccessWorkspace.test.ts +++ b/src/platform/workspace/components/SubscriptionSuccessWorkspace.test.ts @@ -118,11 +118,12 @@ function renderTeamCard(props: Record = {}) { describe('SubscriptionSuccessWorkspace', () => { beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), + const billing = useBillingContext() + Object.assign(billing, { maxSeats: computed(() => mockMaxSeats.value), occupiedSeats: computed(() => mockOccupiedSeats.value) - } as const) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) mockInviteSubmit.mockReset() mockMaxSeats.value = 73 diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index 231e4656a7b..8a77159cd8a 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -128,7 +128,14 @@ function topupResponse( } } +function mockBillingContext() { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) + return billing +} + function renderDialog() { + mockBillingContext() return render(TopUpCreditsDialogContentWorkspace, { global: { plugins: [i18n], @@ -225,7 +232,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('fires a started event before the purchase resolves', async () => { - vi.mocked(useBillingContext().topup).mockResolvedValue( + vi.mocked(mockBillingContext().topup).mockResolvedValue( topupResponse('pending') ) @@ -249,7 +256,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('enters a topup journey on mount and correlates the purchase', async () => { - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(mockBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) renderDialog() await waitFor(() => @@ -288,7 +297,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('does not correlate the operation to a journey replaced mid-request', async () => { let resolveTopup: (value: CreateTopupResponse) => void = () => {} - mockTopup.mockReturnValue( + vi.mocked(mockBillingContext().topup).mockReturnValue( new Promise((resolve) => { resolveTopup = resolve }) @@ -314,7 +323,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { assignment: { status: 'unavailable' } }) resolveTopup(topupResponse('completed')) - await waitFor(() => expect(mockFetchBalance).toHaveBeenCalled()) + await waitFor(() => + expect(mockBillingContext().fetchBalance).toHaveBeenCalled() + ) const phases = ( vi.mocked(useTelemetry()?.trackCheckoutJourneyEvent)?.mock.calls ?? [] @@ -356,7 +367,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(screen.getByText('Total due today')).toBeInTheDocument() expect(screen.getByText('$50.00')).toBeInTheDocument() expect(screen.getByRole('button', { name: 'Pay $50.00' })).toBeEnabled() - expect(useBillingContext().topup).not.toHaveBeenCalled() + expect(mockBillingContext().topup).not.toHaveBeenCalled() }) it('shows the saved-card note when a payment method is on file', async () => { @@ -394,13 +405,15 @@ describe('TopUpCreditsDialogContentWorkspace', () => { await screen.findByRole('button', { name: 'Manage billing' }) ) - expect(useBillingContext().manageSubscription).toHaveBeenCalledTimes(1) + expect(mockBillingContext().manageSubscription).toHaveBeenCalledTimes(1) }) it('reports and surfaces a billing-portal opening failure', async () => { setHasSavedPaymentMethod(false) const failure = new Error('portal down') - vi.mocked(useBillingContext().manageSubscription).mockRejectedValue(failure) + vi.mocked(mockBillingContext().manageSubscription).mockRejectedValue( + failure + ) renderDialog() await clickAddCredits() @@ -423,7 +436,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('explains how to add a payment method when the purchase is refused', async () => { setHasSavedPaymentMethod(false) - vi.mocked(useBillingContext().topup).mockRejectedValue( + vi.mocked(mockBillingContext().topup).mockRejectedValue( new WorkspaceApiError( 'No default payment method is selected.', 400, @@ -604,7 +617,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ])( 'lets the customer start over after a failed challenge when the purchase $rail', async ({ issue }) => { - mockTopup.mockImplementation(issue) + vi.mocked(mockBillingContext().topup).mockImplementation(issue) renderDialog() await clickAddCredits() @@ -635,7 +648,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('ignores a superseded purchase attempt that settles after Start over', async () => { let settleFirst!: (response: CreateTopupResponse) => void - mockTopup + const billing = mockBillingContext() + vi.mocked(billing.topup) .mockImplementationOnce( () => new Promise((resolve) => { @@ -664,10 +678,10 @@ describe('TopUpCreditsDialogContentWorkspace', () => { await userEvent.click(payButton) await nextTick() settleFirst(topupResponse('completed')) - await waitFor(() => expect(mockFetchBalance).toHaveBeenCalled()) + await waitFor(() => expect(billing.fetchBalance).toHaveBeenCalled()) await nextTick() - expect(mockTopup).toHaveBeenCalledTimes(2) + expect(billing.topup).toHaveBeenCalledTimes(2) expect(useDialogStore().closeDialog).not.toHaveBeenCalled() expect(payButton).toBeDisabled() }) @@ -691,7 +705,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('locks pending payment actions and prevents duplicate top-ups', async () => { - vi.mocked(useBillingContext().topup).mockResolvedValue( + vi.mocked(mockBillingContext().topup).mockResolvedValue( topupResponse('pending') ) @@ -713,12 +727,12 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ) payButton.dispatchEvent(new MouseEvent('click', { bubbles: true })) - expect(useBillingContext().topup).toHaveBeenCalledOnce() + expect(mockBillingContext().topup).toHaveBeenCalledOnce() }) it('unlocks payment and reports an operation start failure', async () => { const error = new Error('Operation unavailable') - vi.mocked(useBillingContext().topup).mockResolvedValue( + vi.mocked(mockBillingContext().topup).mockResolvedValue( topupResponse('pending') ) vi.mocked(useBillingOperationStore().startOperation).mockRejectedValue( @@ -751,7 +765,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('refreshes both balance and status after a completed top-up', async () => { - vi.mocked(useBillingContext().topup).mockResolvedValue( + vi.mocked(mockBillingContext().topup).mockResolvedValue( topupResponse('completed') ) @@ -759,8 +773,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { await clickAddCredits() await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) - expect(useBillingContext().fetchBalance).toHaveBeenCalledOnce() - expect(useBillingContext().fetchStatus).toHaveBeenCalledOnce() + expect(mockBillingContext().fetchBalance).toHaveBeenCalledOnce() + expect(mockBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(mockShowSettings).toHaveBeenCalledWith('workspace') expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'topup', @@ -790,7 +804,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('opens Credits settings after a completed local top-up', async () => { mockDistributionTypes.isCloud = false - vi.mocked(useBillingContext().topup).mockResolvedValue( + vi.mocked(mockBillingContext().topup).mockResolvedValue( topupResponse('completed') ) @@ -802,13 +816,13 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('keeps completed top-up telemetry successful when refresh fails', async () => { - vi.mocked(useBillingContext().topup).mockResolvedValue( + vi.mocked(mockBillingContext().topup).mockResolvedValue( topupResponse('completed') ) - vi.mocked(useBillingContext().fetchBalance).mockRejectedValueOnce( + vi.mocked(mockBillingContext().fetchBalance).mockRejectedValueOnce( new Error('balance unavailable') ) - vi.mocked(useBillingContext().fetchStatus).mockRejectedValueOnce( + vi.mocked(mockBillingContext().fetchStatus).mockRejectedValueOnce( new Error('status unavailable') ) @@ -828,7 +842,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('does not refresh balance or status for a pending top-up', async () => { - vi.mocked(useBillingContext().topup).mockResolvedValue( + vi.mocked(mockBillingContext().topup).mockResolvedValue( topupResponse('pending') ) @@ -844,15 +858,15 @@ describe('TopUpCreditsDialogContentWorkspace', () => { autoHandleRequiresAction: true } ) - expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() - expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() + expect(mockBillingContext().fetchBalance).not.toHaveBeenCalled() + expect(mockBillingContext().fetchStatus).not.toHaveBeenCalled() expect(useTelemetry()?.trackBillingEvent).not.toHaveBeenCalledWith( expect.objectContaining({ stage: 'succeeded' }) ) }) it('does not refresh balance or status for a failed top-up', async () => { - vi.mocked(useBillingContext().topup).mockResolvedValue( + vi.mocked(mockBillingContext().topup).mockResolvedValue( topupResponse('failed') ) @@ -860,8 +874,8 @@ describe('TopUpCreditsDialogContentWorkspace', () => { await clickAddCredits() await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) - expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() - expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() + expect(mockBillingContext().fetchBalance).not.toHaveBeenCalled() + expect(mockBillingContext().fetchStatus).not.toHaveBeenCalled() expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'topup', stage: 'failed', @@ -883,7 +897,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('categorizes a thrown topup error via the shared classifier', async () => { const workspaceApiError = new WorkspaceApiError('upstream rejected', 500) - vi.mocked(useBillingContext().topup).mockRejectedValue(workspaceApiError) + vi.mocked(mockBillingContext().topup).mockRejectedValue(workspaceApiError) renderDialog() await clickAddCredits() @@ -908,7 +922,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(screen.getByRole('button', { name: 'Pay $50.00' })).toBeDisabled() - expect(useBillingContext().topup).not.toHaveBeenCalled() + expect(mockBillingContext().topup).not.toHaveBeenCalled() expect( useTelemetry()?.trackApiCreditTopupButtonPurchaseClicked ).not.toHaveBeenCalled() diff --git a/src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts b/src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts index 60d7f3d553f..704c38972d3 100644 --- a/src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts +++ b/src/platform/workspace/components/dialogs/InviteMemberDialogContent.test.ts @@ -64,11 +64,12 @@ function inviteButton() { } beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), + const billing = useBillingContext() + Object.assign(billing, { maxSeats: computed(() => mockMaxSeats.value), occupiedSeats: computed(() => mockOccupiedSeats.value) - } as const) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) Object.assign(useTeamWorkspaceStore(), { pendingInvites: [] }) vi.mocked(useDialogStore().closeDialog).mockImplementation(() => {}) diff --git a/src/platform/workspace/composables/useResubscribe.test.ts b/src/platform/workspace/composables/useResubscribe.test.ts index fb21b97ae88..8b0a03bdb83 100644 --- a/src/platform/workspace/composables/useResubscribe.test.ts +++ b/src/platform/workspace/composables/useResubscribe.test.ts @@ -76,7 +76,14 @@ vi.mock( const apps: App[] = [] +function mockBillingContext() { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) + return billing +} + function useResubscribe(): ReturnType { + mockBillingContext() let result: ReturnType | undefined const app = createApp( defineComponent({ @@ -113,7 +120,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(useBillingContext().resubscribe).not.toHaveBeenCalled() + expect(mockBillingContext().resubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackResubscribeClicked).not.toHaveBeenCalled() expect(state.toastAdd).not.toHaveBeenCalled() expect(isResubscribing.value).toBe(false) @@ -127,7 +134,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(useBillingContext().resubscribe).not.toHaveBeenCalled() + expect(mockBillingContext().resubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackResubscribeClicked).not.toHaveBeenCalled() expect(state.toastAdd).not.toHaveBeenCalled() expect(isResubscribing.value).toBe(false) @@ -143,7 +150,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(useBillingContext().resubscribe).toHaveBeenCalled() + expect(mockBillingContext().resubscribe).toHaveBeenCalled() }) it('refuses whenever the policy denies it', async () => { @@ -155,7 +162,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(useBillingContext().resubscribe).not.toHaveBeenCalled() + expect(mockBillingContext().resubscribe).not.toHaveBeenCalled() }) it('fires a started event before resubscribe resolves', async () => { @@ -181,7 +188,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(useBillingContext().resubscribe).toHaveBeenCalledOnce() + expect(mockBillingContext().resubscribe).toHaveBeenCalledOnce() expect(useTelemetry()?.trackResubscribeClicked).toHaveBeenCalledOnce() expect(useTelemetry()?.trackBillingEvent).not.toHaveBeenCalledWith( expect.objectContaining({ stage: 'succeeded' }) @@ -201,14 +208,14 @@ describe('useResubscribe', () => { }) it('shows an error and resets loading when resubscription fails', async () => { - vi.mocked(useBillingContext().resubscribe).mockRejectedValueOnce( + vi.mocked(mockBillingContext().resubscribe).mockRejectedValueOnce( new Error('Resubscribe failed for person@example.com') ) const { handleResubscribe, isResubscribing } = useResubscribe() await handleResubscribe() - expect(useBillingContext().resubscribe).toHaveBeenCalledOnce() + expect(mockBillingContext().resubscribe).toHaveBeenCalledOnce() expect(state.toastAdd).toHaveBeenCalledWith( expect.objectContaining({ severity: 'error', @@ -231,7 +238,7 @@ describe('useResubscribe', () => { 'checkout initiation rejected', 500 ) - vi.mocked(useBillingContext().resubscribe).mockRejectedValueOnce( + vi.mocked(mockBillingContext().resubscribe).mockRejectedValueOnce( authStoreError ) const { handleResubscribe } = useResubscribe() @@ -253,7 +260,7 @@ describe('useResubscribe', () => { it('categorizes an AuthStoreError with no status as a network failure, not an api rejection', async () => { state.shouldUseWorkspaceBilling = false const authStoreError = new AuthStoreError('offline') - vi.mocked(useBillingContext().resubscribe).mockRejectedValueOnce( + vi.mocked(mockBillingContext().resubscribe).mockRejectedValueOnce( authStoreError ) const { handleResubscribe } = useResubscribe() @@ -271,7 +278,7 @@ describe('useResubscribe', () => { it('emits started before the awaited resubscribe call resolves', async () => { const callOrder: string[] = [] - vi.mocked(useBillingContext().resubscribe).mockImplementation(async () => { + vi.mocked(mockBillingContext().resubscribe).mockImplementation(async () => { callOrder.push('resubscribe') }) vi.mocked(useTelemetry()?.trackBillingEvent)?.mockImplementation( diff --git a/src/platform/workspace/stores/billingOperationStore.test.ts b/src/platform/workspace/stores/billingOperationStore.test.ts index e5667d4194d..89439c9c40d 100644 --- a/src/platform/workspace/stores/billingOperationStore.test.ts +++ b/src/platform/workspace/stores/billingOperationStore.test.ts @@ -451,6 +451,8 @@ describe('billingOperationStore', () => { }) it('updates status and shows toast on success', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', @@ -467,11 +469,9 @@ describe('billingOperationStore', () => { expect(store.hasPendingOperations).toBe(false) expect(mockRefreshCapabilities).toHaveBeenCalledOnce() - expect( - useBillingContext().reconcileSubscriptionSuccess - ).toHaveBeenCalledOnce() - expect(useBillingContext().fetchStatus).not.toHaveBeenCalled() - expect(useBillingContext().fetchBalance).not.toHaveBeenCalled() + expect(billing.reconcileSubscriptionSuccess).toHaveBeenCalledOnce() + expect(billing.fetchStatus).not.toHaveBeenCalled() + expect(billing.fetchBalance).not.toHaveBeenCalled() expect(useToastStore().add).toHaveBeenCalledWith({ severity: 'success', @@ -880,16 +880,18 @@ describe('billingOperationStore', () => { }) it('resolves the terminal promise even if reconciliation throws synchronously', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', started_at: new Date().toISOString() }) - vi.mocked( - useBillingContext().reconcileSubscriptionSuccess - ).mockImplementationOnce(() => { - throw new Error('reconcile failed') - }) + vi.mocked(billing.reconcileSubscriptionSuccess).mockImplementationOnce( + () => { + throw new Error('reconcile failed') + } + ) const store = useBillingOperationStore() const terminal = store.startOperation('op-1', 'subscription') @@ -2456,6 +2458,8 @@ describe('billingOperationStore', () => { }) it('resolves with the succeeded operation and refreshes status', async () => { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', @@ -2469,7 +2473,7 @@ describe('billingOperationStore', () => { const operation = await terminal expect(operation.status).toBe('succeeded') - expect(useBillingContext().fetchStatus).toHaveBeenCalled() + expect(billing.fetchStatus).toHaveBeenCalled() expect( useTeamWorkspaceStore().updateActiveWorkspace ).toHaveBeenCalledWith({ @@ -2486,7 +2490,9 @@ describe('billingOperationStore', () => { }) it('resolves the terminal outcome even when the post-success refresh fails', async () => { - vi.mocked(useBillingContext().fetchStatus).mockRejectedValueOnce( + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) + vi.mocked(billing.fetchStatus).mockRejectedValueOnce( new Error('refresh failed') ) vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ diff --git a/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts b/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts index b7f8170dc4d..b8e3dfa2446 100644 --- a/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts +++ b/src/renderer/extensions/firstRunTour/tour/useFirstRunTourController.test.ts @@ -173,10 +173,9 @@ function mountRunButton( } beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), - canRunWorkflows: computed(() => mocks.canRunWorkflows.value) - } as const) + const billing = useBillingContext() + billing.canRunWorkflows = computed(() => mocks.canRunWorkflows.value) + vi.mocked(useBillingContext).mockReturnValue(billing) Object.assign(useOnboardingTourStore(), { activeTour: diff --git a/src/renderer/extensions/linearMode/LinearControls.test.ts b/src/renderer/extensions/linearMode/LinearControls.test.ts index 6a895e16716..6b464b19a88 100644 --- a/src/renderer/extensions/linearMode/LinearControls.test.ts +++ b/src/renderer/extensions/linearMode/LinearControls.test.ts @@ -104,10 +104,9 @@ function renderControls({ canRunWorkflows?: boolean mobile?: boolean } = {}) { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), - canRunWorkflows: computed(() => canRunWorkflows) - } as const) + const billing = useBillingContext() + billing.canRunWorkflows = computed(() => canRunWorkflows) + vi.mocked(useBillingContext).mockReturnValue(billing) const pinia = getActivePinia()! diff --git a/src/services/dialogService.downgrade.test.ts b/src/services/dialogService.downgrade.test.ts index 8a47dccfa0a..bea6070eb7c 100644 --- a/src/services/dialogService.downgrade.test.ts +++ b/src/services/dialogService.downgrade.test.ts @@ -43,12 +43,13 @@ vi.mock(import('@/i18n'), () => ({ vi.mock(import('@/platform/telemetry')) beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), + const billing = useBillingContext() + Object.assign(billing, { canAccessSubscriptionFeatures: computed(() => true), isFreeTier: computed(() => false), type: computed(() => 'legacy') - } as const) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) }) vi.mock(import('@/platform/distribution/types'), () => ({ diff --git a/src/services/dialogService.renderer.test.ts b/src/services/dialogService.renderer.test.ts index dbf67e8b703..728dc47bb1c 100644 --- a/src/services/dialogService.renderer.test.ts +++ b/src/services/dialogService.renderer.test.ts @@ -5,7 +5,7 @@ import { useBillingContext } from '@/composables/billing/useBillingContext' * Reka-migrated dialog, the dialog stack item must carry `renderer: 'reka'`. * Catches accidental reverts of the Reka renderer flip. */ -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' vi.mock(import('@/i18n'), () => ({ t: (key: string) => key @@ -14,13 +14,14 @@ vi.mock(import('@/i18n'), () => ({ vi.mock(import('@/platform/telemetry')) beforeEach(() => { - vi.mocked(useBillingContext).mockReturnValue({ - ...useBillingContext(), + const billing = useBillingContext() + Object.assign(billing, { canAccessSubscriptionFeatures: computed(() => true), isTeamPlan: computed(() => false), tier: computed(() => 'STANDARD'), type: computed(() => 'legacy') - } as const) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) }) vi.mock(import('@/platform/distribution/types'), () => ({ From 416be458192d8ed64911f941173382ea9e98573f Mon Sep 17 00:00:00 2001 From: Amp Date: Tue, 15 Sep 2026 05:56:40 +0000 Subject: [PATCH 3/4] test: centralize billing context setup Amp-Thread-ID: https://ampcode.com/threads/T-01a0a2f9-a153-7099-9a4a-1dc942db28ca --- .../dialog/content/setting/CreditsPanel.test.ts | 8 +++----- .../subscription/components/SubscribeToRun.test.ts | 5 +++-- .../components/SubscriptionFooterLinks.test.ts | 5 +++-- .../useAccountPreconditionDialog.test.ts | 8 +++----- .../composables/usePaymentReturnUrlLoader.test.ts | 11 ++++------- .../composables/useSubscriptionActions.test.ts | 8 +++----- .../workspace/components/InviteMembersForm.test.ts | 4 ++-- .../TopUpCreditsDialogContentWorkspace.test.ts | 8 +------- .../workspace/composables/useResubscribe.test.ts | 8 +------- .../workspace/stores/billingOperationStore.test.ts | 14 +++++--------- src/utils/__tests__/mockBillingContext.ts | 9 +++++++++ 11 files changed, 37 insertions(+), 51 deletions(-) create mode 100644 src/utils/__tests__/mockBillingContext.ts diff --git a/src/components/dialog/content/setting/CreditsPanel.test.ts b/src/components/dialog/content/setting/CreditsPanel.test.ts index 7f31e3c4ac4..ad02f44d21a 100644 --- a/src/components/dialog/content/setting/CreditsPanel.test.ts +++ b/src/components/dialog/content/setting/CreditsPanel.test.ts @@ -5,7 +5,7 @@ import { computed, defineComponent, h, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' import type { BalanceInfo } from '@/composables/billing/types' -import { useBillingContext } from '@/composables/billing/useBillingContext' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' import CreditsPanel from './CreditsPanel.vue' @@ -75,8 +75,7 @@ describe('CreditsPanel', () => { } it('opens the billing portal for the active billing rail', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() const user = userEvent.setup() renderComponent() @@ -86,8 +85,7 @@ describe('CreditsPanel', () => { }) it('refreshes activity on a balance change but not on first hydration', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() const balance = ref(null) billing.balance = computed(() => balance.value) renderComponent() diff --git a/src/platform/cloud/subscription/components/SubscribeToRun.test.ts b/src/platform/cloud/subscription/components/SubscribeToRun.test.ts index 1ba2cb1895a..27946b940e6 100644 --- a/src/platform/cloud/subscription/components/SubscribeToRun.test.ts +++ b/src/platform/cloud/subscription/components/SubscribeToRun.test.ts @@ -5,6 +5,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { computed, ref } from 'vue' import { createI18n } from 'vue-i18n' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' + import SubscribeToRun from './SubscribeToRun.vue' const mockCanManageSubscription = ref(true) @@ -59,8 +61,7 @@ const i18n = createI18n({ }) function renderButton() { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + mockBillingContext() const user = userEvent.setup() const result = render(SubscribeToRun, { global: { diff --git a/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts b/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts index f9f71276f8b..5ad62f1468b 100644 --- a/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts +++ b/src/platform/cloud/subscription/components/SubscriptionFooterLinks.test.ts @@ -6,6 +6,8 @@ import { ref } from 'vue' import type { ComponentProps } from 'vue-component-type-helpers' import { createI18n } from 'vue-i18n' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' + import SubscriptionFooterLinks from './SubscriptionFooterLinks.vue' const state = vi.hoisted(() => ({ @@ -62,8 +64,7 @@ const i18n = createI18n({ function renderComponent( props: Partial> = {} ) { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + mockBillingContext() return render(SubscriptionFooterLinks, { props, global: { diff --git a/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts b/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts index 9bf5659864d..816130c7c6d 100644 --- a/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts +++ b/src/platform/cloud/subscription/composables/useAccountPreconditionDialog.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { useBillingContext } from '@/composables/billing/useBillingContext' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' import { useAccountPreconditionDialog } from './useAccountPreconditionDialog' @@ -57,8 +57,7 @@ describe('useAccountPreconditionDialog', () => { }) it('refreshes the billing snapshot on a credit precondition so exhausted-state surfaces converge', () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() useAccountPreconditionDialog().open('credits') expect(billing.fetchStatus).toHaveBeenCalledTimes(1) @@ -66,8 +65,7 @@ describe('useAccountPreconditionDialog', () => { }) it('does not touch billing state for non-credit preconditions', () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() useAccountPreconditionDialog().open('subscription') expect(billing.fetchStatus).not.toHaveBeenCalled() diff --git a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts index 390aa1365a4..777db682394 100644 --- a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts +++ b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts @@ -1,7 +1,7 @@ -import { useBillingContext } from '@/composables/billing/useBillingContext' import { beforeEach, describe, expect, it, vi } from 'vitest' import { stripPaymentReturnParams } from '@/platform/cloud/subscription/utils/paymentReturnUrl' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' import { usePaymentReturnUrlLoader } from './usePaymentReturnUrlLoader' @@ -28,8 +28,7 @@ describe('usePaymentReturnUrlLoader', () => { }) it('refreshes billing after bootstrap strips Stripe return params', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() window.history.replaceState( {}, '', @@ -45,8 +44,7 @@ describe('usePaymentReturnUrlLoader', () => { }) it('does nothing on an ordinary page load', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() window.history.replaceState({}, '', '/?workspace=ws-1') const { loadPaymentReturnFromUrl } = usePaymentReturnUrlLoader() @@ -56,8 +54,7 @@ describe('usePaymentReturnUrlLoader', () => { }) it('does not start embedded recovery while the flag is off', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() mocks.embeddedCheckoutEnabled = false window.history.replaceState( {}, diff --git a/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts b/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts index a6dd775baf6..bdbeee0d3e5 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts @@ -1,10 +1,10 @@ -import { useBillingContext } from '@/composables/billing/useBillingContext' import { useToastStore } from '@/platform/updates/common/toastStore' import { useCommandStore } from '@/stores/commandStore' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useAuthActions } from '@/composables/auth/useAuthActions' import { useSubscriptionActions } from '@/platform/cloud/subscription/composables/useSubscriptionActions' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' const mockShowTopUpCreditsDialog = vi.fn() const mockExecute = vi.fn['execute']>( @@ -161,8 +161,7 @@ describe('useSubscriptionActions', () => { describe('handleRefresh', () => { it('should refresh balance and status through the billing facade', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() const { handleRefresh } = useSubscriptionActions() await handleRefresh() @@ -172,8 +171,7 @@ describe('useSubscriptionActions', () => { }) it('swallows refresh failures without surfacing a toast', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() vi.mocked(billing.fetchBalance).mockRejectedValueOnce( new Error('Fetch failed') ) diff --git a/src/platform/workspace/components/InviteMembersForm.test.ts b/src/platform/workspace/components/InviteMembersForm.test.ts index 3ad2215e203..15a8a2a7f3e 100644 --- a/src/platform/workspace/components/InviteMembersForm.test.ts +++ b/src/platform/workspace/components/InviteMembersForm.test.ts @@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' import { useTelemetry } from '@/platform/telemetry' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' import InviteMembersForm from './InviteMembersForm.vue' @@ -46,8 +47,7 @@ function pendingInviteFor(email: string): WorkspacePendingInvite { } function renderForm(props: Record = {}) { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + mockBillingContext() const user = userEvent.setup() const result = render(InviteMembersForm, { props: { diff --git a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts index 8a77159cd8a..f19e7f233d8 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -4,7 +4,6 @@ import { setPersistence } from 'firebase/auth' -import { useBillingContext } from '@/composables/billing/useBillingContext' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { @@ -28,6 +27,7 @@ import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import type { CreateTopupResponse } from '@/platform/workspace/api/workspaceApi' import { billingOperation } from '@/platform/workspace/composables/billingOperationTestUtils' import type { BillingOperation } from '@/platform/workspace/composables/billingOperationTestUtils' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' import TopUpCreditsDialogContentWorkspace from './TopUpCreditsDialogContentWorkspace.vue' @@ -128,12 +128,6 @@ function topupResponse( } } -function mockBillingContext() { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) - return billing -} - function renderDialog() { mockBillingContext() return render(TopUpCreditsDialogContentWorkspace, { diff --git a/src/platform/workspace/composables/useResubscribe.test.ts b/src/platform/workspace/composables/useResubscribe.test.ts index 8b0a03bdb83..69e23f4b650 100644 --- a/src/platform/workspace/composables/useResubscribe.test.ts +++ b/src/platform/workspace/composables/useResubscribe.test.ts @@ -1,4 +1,3 @@ -import { useBillingContext } from '@/composables/billing/useBillingContext' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createApp, defineComponent } from 'vue' import type { App } from 'vue' @@ -7,6 +6,7 @@ import { createI18n } from 'vue-i18n' import { useTelemetry } from '@/platform/telemetry' import { AuthStoreError } from '@/stores/authStore' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' import { useResubscribe as createResubscribe } from './useResubscribe' @@ -76,12 +76,6 @@ vi.mock( const apps: App[] = [] -function mockBillingContext() { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) - return billing -} - function useResubscribe(): ReturnType { mockBillingContext() let result: ReturnType | undefined diff --git a/src/platform/workspace/stores/billingOperationStore.test.ts b/src/platform/workspace/stores/billingOperationStore.test.ts index 89439c9c40d..4ec360b34c5 100644 --- a/src/platform/workspace/stores/billingOperationStore.test.ts +++ b/src/platform/workspace/stores/billingOperationStore.test.ts @@ -1,4 +1,3 @@ -import { useBillingContext } from '@/composables/billing/useBillingContext' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { bindOperationToCheckoutJourney, @@ -13,6 +12,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { useTelemetry } from '@/platform/telemetry' import type { BillingOpStatusResponse } from '@/platform/workspace/api/workspaceApi' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' const { mockHandleNextAction, mockLoadStripe, mockFeatureFlags } = vi.hoisted( () => ({ @@ -451,8 +451,7 @@ describe('billingOperationStore', () => { }) it('updates status and shows toast on success', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', @@ -880,8 +879,7 @@ describe('billingOperationStore', () => { }) it('resolves the terminal promise even if reconciliation throws synchronously', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', @@ -2458,8 +2456,7 @@ describe('billingOperationStore', () => { }) it('resolves with the succeeded operation and refreshes status', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', @@ -2490,8 +2487,7 @@ describe('billingOperationStore', () => { }) it('resolves the terminal outcome even when the post-success refresh fails', async () => { - const billing = useBillingContext() - vi.mocked(useBillingContext).mockReturnValue(billing) + const billing = mockBillingContext() vi.mocked(billing.fetchStatus).mockRejectedValueOnce( new Error('refresh failed') ) diff --git a/src/utils/__tests__/mockBillingContext.ts b/src/utils/__tests__/mockBillingContext.ts new file mode 100644 index 00000000000..bc33a94c105 --- /dev/null +++ b/src/utils/__tests__/mockBillingContext.ts @@ -0,0 +1,9 @@ +import { vi } from 'vitest' + +import { useBillingContext } from '@/composables/billing/useBillingContext' + +export function mockBillingContext() { + const billing = useBillingContext() + vi.mocked(useBillingContext).mockReturnValue(billing) + return billing +} From 55ec26838575e38ca1749525ef23ecfea0315823 Mon Sep 17 00:00:00 2001 From: Amp Date: Tue, 15 Sep 2026 23:54:32 +0000 Subject: [PATCH 4/4] test: isolate billing redirect fixture Amp-Thread-ID: https://ampcode.com/threads/T-01a0a2f9-a153-7099-9a4a-1dc942db28ca --- .../CloudSubscriptionRedirectView.test.ts | 45 +++++++++++-------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts b/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts index 3d826b51190..abc71c360c0 100644 --- a/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts +++ b/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts @@ -36,9 +36,6 @@ vi.mock(import('@/composables/useErrorHandling'), () => ({ }) })) -const canAccessSubscriptionFeatures = ref(false) -const teamCreditStops = ref(null) - vi.mock(import('@/composables/billing/useBillingContext')) const mockShowPricingTable = vi.hoisted(() => vi.fn()) @@ -81,6 +78,20 @@ const TEAM_CREDIT_STOPS = { ] } satisfies TeamCreditStops +function installBillingContextFixture() { + const billing = useBillingContext() + const canAccessSubscriptionFeatures = ref(false) + const teamCreditStops = ref(TEAM_CREDIT_STOPS) + Object.assign(billing, { + isInitialized: ref(true), + canAccessSubscriptionFeatures: computed( + () => canAccessSubscriptionFeatures.value + ), + teamCreditStops: computed(() => teamCreditStops.value) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) +} + const createI18nInstance = () => createI18n({ legacy: false, @@ -124,17 +135,7 @@ const mountView = async (query: Record) => { describe('CloudSubscriptionRedirectView', () => { beforeEach(() => { mockQuery = {} - canAccessSubscriptionFeatures.value = false - teamCreditStops.value = TEAM_CREDIT_STOPS - const billing = useBillingContext() - Object.assign(billing, { - isInitialized: ref(true), - canAccessSubscriptionFeatures: computed( - () => canAccessSubscriptionFeatures.value - ), - teamCreditStops: computed(() => teamCreditStops.value) - }) - vi.mocked(useBillingContext).mockReturnValue(billing) + installBillingContextFixture() }) test('redirects to home when subscriptionType is missing', async () => { @@ -178,7 +179,9 @@ describe('CloudSubscriptionRedirectView', () => { }) test('opens billing portal when subscription is already active', async () => { - canAccessSubscriptionFeatures.value = true + Object.assign(useBillingContext(), { + canAccessSubscriptionFeatures: computed(() => true) + }) await mountView({ tier: 'creator' }) @@ -227,7 +230,9 @@ describe('CloudSubscriptionRedirectView', () => { }) test('opens the generic team pricing table when plan loading fails', async () => { - teamCreditStops.value = null + Object.assign(useBillingContext(), { + teamCreditStops: computed(() => null) + }) const plansError = new Error('plans down') vi.mocked(useBillingContext().fetchPlans).mockRejectedValue(plansError) @@ -263,7 +268,9 @@ describe('CloudSubscriptionRedirectView', () => { }) test('routes a personal tier in an active Team workspace to workspace subscription management', async () => { - canAccessSubscriptionFeatures.value = true + Object.assign(useBillingContext(), { + canAccessSubscriptionFeatures: computed(() => true) + }) await mountView({ tier: 'creator', cycle: 'yearly' }) @@ -276,7 +283,9 @@ describe('CloudSubscriptionRedirectView', () => { }) test('routes an active founder subscription to facade management', async () => { - canAccessSubscriptionFeatures.value = true + Object.assign(useBillingContext(), { + canAccessSubscriptionFeatures: computed(() => true) + }) await mountView({ tier: 'founder' })