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..ad02f44d21a 100644 --- a/src/components/dialog/content/setting/CreditsPanel.test.ts +++ b/src/components/dialog/content/setting/CreditsPanel.test.ts @@ -1,31 +1,15 @@ 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 { describe, expect, it, vi } from 'vitest' +import { computed, defineComponent, h, nextTick, ref } from 'vue' import { createI18n } from 'vue-i18n' import type { BalanceInfo } from '@/composables/billing/types' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' 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 - }) - } - } -) +vi.mock(import('@/composables/billing/useBillingContext')) const refreshActivity = vi.hoisted(() => vi.fn()) vi.mock(import('./UsageLogsTable.vue'), async () => { @@ -84,10 +68,6 @@ function makeBalance(amountMicros: number): BalanceInfo { } describe('CreditsPanel', () => { - beforeEach(() => { - billingMocks.balance.value = null - }) - function renderComponent() { return render(CreditsPanel, { global: { plugins: [i18n], stubs: { Divider: true } } @@ -95,22 +75,26 @@ describe('CreditsPanel', () => { } it('opens the billing portal for the active billing rail', async () => { + const billing = mockBillingContext() const user = userEvent.setup() renderComponent() await user.click(screen.getByRole('button', { name: /Invoice History/ })) - expect(billingMocks.manageSubscription).toHaveBeenCalledOnce() + expect(billing.manageSubscription).toHaveBeenCalledOnce() }) it('refreshes activity on a balance change but not on first hydration', async () => { + const billing = mockBillingContext() + const balance = ref(null) + billing.balance = computed(() => balance.value) 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..f0689d698cf 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,19 @@ vi.mock(import('@/platform/settings/composables/useSettingsDialog'), () => ({ const originalWindowOpen = window.open beforeEach(() => { + const billing = useBillingContext() + Object.assign(billing, { + canAccessSubscriptionFeatures: computed( + () => mockCanAccessSubscriptionFeatures.value + ), + tier: computed(() => mockTier.value), + subscription: computed(() => mockSubscription.value), + balance: computed(() => mockBalance.value), + isLoading: mockIsLoading, + isTeamPlan: computed(() => mockIsTeamPlan.value) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) + window.open = vi.fn() }) @@ -65,7 +79,6 @@ function makeSubscription( } } -const mockFetchBalance = vi.fn().mockResolvedValue(undefined) const mockCanAccessSubscriptionFeatures = ref(true) const mockTier = ref('CREATOR') const mockSubscription = ref(makeSubscription()) @@ -75,17 +88,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 +177,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..43732800d82 --- /dev/null +++ b/src/composables/billing/__mocks__/useBillingContext.ts @@ -0,0 +1,50 @@ +import { vi } from 'vitest' +import { computed, ref } from 'vue' + +import type { BillingContext } from '../types' +import type { useBillingContext as realUseBillingContext } from '../useBillingContext' + +function createBillingContextMock(): BillingContext { + return { + 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 () => {}) + } +} + +export const useBillingContext = vi.fn( + createBillingContextMock +) diff --git a/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts b/src/platform/cloud/onboarding/CloudSubscriptionRedirectView.test.ts index 8e7678df6fd..abc71c360c0 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,7 @@ 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() -})) - -vi.mock(import('@/composables/billing/useBillingContext'), () => ({ - useBillingContext: () => subscriptionMocks -})) +vi.mock(import('@/composables/billing/useBillingContext')) const mockShowPricingTable = vi.hoisted(() => vi.fn()) vi.mock( @@ -87,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, @@ -130,12 +135,7 @@ 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) + installBillingContextFixture() }) test('redirects to home when subscriptionType is missing', async () => { @@ -179,12 +179,14 @@ describe('CloudSubscriptionRedirectView', () => { }) test('opens billing portal when subscription is already active', async () => { - subscriptionMocks.canAccessSubscriptionFeatures.value = true + Object.assign(useBillingContext(), { + canAccessSubscriptionFeatures: computed(() => 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 +230,11 @@ describe('CloudSubscriptionRedirectView', () => { }) test('opens the generic team pricing table when plan loading fails', async () => { - subscriptionMocks.teamCreditStops.value = null + Object.assign(useBillingContext(), { + teamCreditStops: computed(() => 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 +268,13 @@ describe('CloudSubscriptionRedirectView', () => { }) test('routes a personal tier in an active Team workspace to workspace subscription management', async () => { - subscriptionMocks.canAccessSubscriptionFeatures.value = true + Object.assign(useBillingContext(), { + canAccessSubscriptionFeatures: computed(() => 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 +283,13 @@ describe('CloudSubscriptionRedirectView', () => { }) test('routes an active founder subscription to facade management', async () => { - subscriptionMocks.canAccessSubscriptionFeatures.value = true + Object.assign(useBillingContext(), { + canAccessSubscriptionFeatures: computed(() => 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..b791b4b0b48 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,10 @@ const i18n = createI18n({ describe('FreeTierQuota', () => { beforeEach(() => { + 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 8aebaefba82..27946b940e6 100644 --- a/src/platform/cloud/subscription/components/SubscribeToRun.test.ts +++ b/src/platform/cloud/subscription/components/SubscribeToRun.test.ts @@ -1,20 +1,18 @@ +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' import { computed, ref } from 'vue' import { createI18n } from 'vue-i18n' +import { mockBillingContext } from '@/utils/__tests__/mockBillingContext' + 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'), @@ -63,6 +61,7 @@ const i18n = createI18n({ }) function renderButton() { + mockBillingContext() const user = userEvent.setup() const result = render(SubscribeToRun, { global: { @@ -101,7 +100,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 +109,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..5ad62f1468b 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' @@ -5,11 +6,12 @@ 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(() => ({ isCloud: true, - manageSubscription: vi.fn(), handleLearnMoreClick: vi.fn(), handleMessageSupport: vi.fn() })) @@ -24,11 +26,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: () => ({ @@ -66,6 +64,7 @@ const i18n = createI18n({ function renderComponent( props: Partial> = {} ) { + mockBillingContext() return render(SubscriptionFooterLinks, { props, global: { @@ -134,7 +133,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 +143,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..816130c7c6d 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 { mockBillingContext } from '@/utils/__tests__/mockBillingContext' + 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', () => { @@ -62,16 +57,18 @@ describe('useAccountPreconditionDialog', () => { }) it('refreshes the billing snapshot on a credit precondition so exhausted-state surfaces converge', () => { + const billing = mockBillingContext() useAccountPreconditionDialog().open('credits') - expect(mockBilling.fetchStatus).toHaveBeenCalledTimes(1) - expect(mockBilling.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 = mockBillingContext() useAccountPreconditionDialog().open('subscription') - expect(mockBilling.fetchStatus).not.toHaveBeenCalled() - expect(mockBilling.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 0ac559d7b5c..777db682394 100644 --- a/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts +++ b/src/platform/cloud/subscription/composables/usePaymentReturnUrlLoader.test.ts @@ -1,17 +1,15 @@ 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' 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: () => ({ @@ -30,6 +28,7 @@ describe('usePaymentReturnUrlLoader', () => { }) it('refreshes billing after bootstrap strips Stripe return params', async () => { + const billing = mockBillingContext() window.history.replaceState( {}, '', @@ -41,19 +40,21 @@ describe('usePaymentReturnUrlLoader', () => { await loadPaymentReturnFromUrl() expect(window.location.search).toBe('?workspace=ws-1') - expect(mocks.fetchStatus).toHaveBeenCalledOnce() + expect(billing.fetchStatus).toHaveBeenCalledOnce() }) it('does nothing on an ordinary page load', async () => { + const billing = mockBillingContext() window.history.replaceState({}, '', '/?workspace=ws-1') const { loadPaymentReturnFromUrl } = usePaymentReturnUrlLoader() await loadPaymentReturnFromUrl() - expect(mocks.fetchStatus).not.toHaveBeenCalled() + expect(billing.fetchStatus).not.toHaveBeenCalled() }) it('does not start embedded recovery while the flag is off', async () => { + const billing = mockBillingContext() mocks.embeddedCheckoutEnabled = false window.history.replaceState( {}, @@ -64,6 +65,6 @@ describe('usePaymentReturnUrlLoader', () => { await usePaymentReturnUrlLoader().loadPaymentReturnFromUrl() - expect(mocks.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 52f7ec1f614..32cfa078dac 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,17 @@ const TEAM_CREDIT_STOPS = { describe('usePricingTableUrlLoader', () => { beforeEach(() => { + const billing = useBillingContext() + billing.teamCreditStops = computed(() => mockTeamCreditStops.value) + vi.mocked(useBillingContext).mockReturnValue(billing) + mockRouteQuery.value = {} mockPermissions.value = { canManageSubscription: true } mockCanOpenPricingSurface.value = true mockInitializeCapabilities.mockClear() mockInitializeCapabilities.mockResolvedValue(undefined) mockTeamCreditStops.value = TEAM_CREDIT_STOPS - mockFetchPlans.mockResolvedValue(undefined) + vi.mocked(billing.fetchPlans).mockResolvedValue(undefined) mockShowPricingTable.mockResolvedValue(undefined) preservedQueryMocks.mergePreservedQueryIntoQuery.mockReturnValue(null) }) @@ -385,14 +383,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 +410,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..bdbeee0d3e5 100644 --- a/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscriptionActions.test.ts @@ -4,9 +4,8 @@ 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 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: () => ({ @@ -167,16 +161,20 @@ describe('useSubscriptionActions', () => { describe('handleRefresh', () => { it('should refresh balance and status through the billing facade', async () => { + const billing = mockBillingContext() const { handleRefresh } = useSubscriptionActions() await handleRefresh() - expect(mockBillingFetchBalance).toHaveBeenCalledOnce() - expect(mockFetchStatus).toHaveBeenCalledOnce() + expect(billing.fetchBalance).toHaveBeenCalledOnce() + expect(billing.fetchStatus).toHaveBeenCalledOnce() expect(useAuthActions().fetchBalance).not.toHaveBeenCalled() }) it('swallows refresh failures without surfacing a toast', async () => { - mockBillingFetchBalance.mockRejectedValueOnce(new Error('Fetch failed')) + const billing = mockBillingContext() + vi.mocked(billing.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..9480cbd06ba 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,17 @@ 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(() => { + const billing = useBillingContext() + Object.assign(billing, { + canAccessSubscriptionFeatures: computed(() => true), + isFreeTier: computed(() => false), + type: computed(() => 'legacy') }) -})) + vi.mocked(useBillingContext).mockReturnValue(billing) +}) + +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..15a8a2a7f3e 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' @@ -5,19 +6,17 @@ 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' 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 @@ -48,6 +47,7 @@ function pendingInviteFor(email: string): WorkspacePendingInvite { } function renderForm(props: Record = {}) { + mockBillingContext() const user = userEvent.setup() const result = render(InviteMembersForm, { props: { @@ -76,7 +76,7 @@ describe('InviteMembersForm', () => { vi.mocked(useTeamWorkspaceStore().fetchPendingInvites).mockResolvedValue([ ...useTeamWorkspaceStore().pendingInvites ]) - mockFetchStatus.mockResolvedValue(undefined) + vi.mocked(useTeamWorkspaceStore().createInvite).mockImplementation( async (email: string) => pendingInviteFor(email) ) @@ -123,22 +123,24 @@ 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) const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) const { user, emitted } = renderForm() + vi.mocked(useBillingContext().fetchStatus).mockRejectedValueOnce( + refreshError + ) await user.type(emailInput(), 'a@b.com{Enter}') await user.click(submitButton()) 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 +257,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..a0e25cbf3ba 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'], @@ -79,7 +72,11 @@ beforeEach(() => { describe('PricingTableWorkspace credit allotment copy', () => { beforeEach(() => { + const billing = useBillingContext() state.plans = [] + 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 d6fb507bfe0..bd74c8a5d41 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,26 @@ function renderComponent({ stubFooter = true } = {}) { describe('SubscriptionPanelContentWorkspace', () => { beforeEach(() => { + const billing = useBillingContext() + Object.assign(billing, { + 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 + }) + vi.mocked(billing.getMaxSeats).mockReturnValue(5) + vi.mocked(useBillingContext).mockReturnValue(billing) + mockDistributionState.isCloud = true mockSubscriptionStatus.value = 'active' mockBillingStatus.value = 'paid' @@ -675,10 +670,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 +698,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 +761,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 +843,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 +875,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 +931,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 +1029,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 +1073,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 +1137,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..54d9334ce1a 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,13 @@ function renderTeamCard(props: Record = {}) { describe('SubscriptionSuccessWorkspace', () => { beforeEach(() => { + const billing = useBillingContext() + Object.assign(billing, { + maxSeats: computed(() => mockMaxSeats.value), + occupiedSeats: computed(() => mockOccupiedSeats.value) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) + 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..f19e7f233d8 100644 --- a/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts +++ b/src/platform/workspace/components/TopUpCreditsDialogContentWorkspace.test.ts @@ -27,19 +27,15 @@ 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' -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'), @@ -140,6 +129,7 @@ function topupResponse( } function renderDialog() { + mockBillingContext() return render(TopUpCreditsDialogContentWorkspace, { global: { plugins: [i18n], @@ -225,8 +215,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { setCanTopUp(true) setIsAddingCredits(false) setTopupActionOperation(undefined) - mockFetchBalance.mockResolvedValue(undefined) - mockFetchStatus.mockResolvedValue(undefined) + setHasSavedPaymentMethod(true) vi.mocked(useBillingOperationStore().startOperation).mockImplementation( () => { @@ -237,7 +226,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('fires a started event before the purchase resolves', async () => { - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(mockBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) renderDialog() await clickAddCredits() @@ -259,7 +250,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(() => @@ -298,7 +291,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 }) @@ -324,7 +317,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 ?? [] @@ -336,8 +331,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 +361,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(mockBillingContext().topup).not.toHaveBeenCalled() }) it('shows the saved-card note when a payment method is on file', async () => { @@ -398,7 +391,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 +399,15 @@ describe('TopUpCreditsDialogContentWorkspace', () => { await screen.findByRole('button', { name: 'Manage billing' }) ) - expect(mockManageSubscription).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') - mockManageSubscription.mockRejectedValue(failure) + vi.mocked(mockBillingContext().manageSubscription).mockRejectedValue( + failure + ) renderDialog() await clickAddCredits() @@ -436,7 +430,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('explains how to add a payment method when the purchase is refused', async () => { setHasSavedPaymentMethod(false) - mockTopup.mockRejectedValue( + vi.mocked(mockBillingContext().topup).mockRejectedValue( new WorkspaceApiError( 'No default payment method is selected.', 400, @@ -617,7 +611,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() @@ -648,7 +642,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) => { @@ -677,10 +672,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() }) @@ -704,7 +699,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('locks pending payment actions and prevents duplicate top-ups', async () => { - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(mockBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) renderDialog() await clickAddCredits() @@ -724,12 +721,14 @@ describe('TopUpCreditsDialogContentWorkspace', () => { ) payButton.dispatchEvent(new MouseEvent('click', { bubbles: true })) - expect(mockTopup).toHaveBeenCalledOnce() + expect(mockBillingContext().topup).toHaveBeenCalledOnce() }) it('unlocks payment and reports an operation start failure', async () => { const error = new Error('Operation unavailable') - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(mockBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) vi.mocked(useBillingOperationStore().startOperation).mockRejectedValue( error ) @@ -760,14 +759,16 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('refreshes both balance and status after a completed top-up', async () => { - mockTopup.mockResolvedValue(topupResponse('completed')) + vi.mocked(mockBillingContext().topup).mockResolvedValue( + topupResponse('completed') + ) renderDialog() await clickAddCredits() await userEvent.click(screen.getByRole('button', { name: 'Pay $50.00' })) - expect(mockFetchBalance).toHaveBeenCalledOnce() - expect(mockFetchStatus).toHaveBeenCalledOnce() + expect(mockBillingContext().fetchBalance).toHaveBeenCalledOnce() + expect(mockBillingContext().fetchStatus).toHaveBeenCalledOnce() expect(mockShowSettings).toHaveBeenCalledWith('workspace') expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'topup', @@ -797,7 +798,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { it('opens Credits settings after a completed local top-up', async () => { mockDistributionTypes.isCloud = false - mockTopup.mockResolvedValue(topupResponse('completed')) + vi.mocked(mockBillingContext().topup).mockResolvedValue( + topupResponse('completed') + ) renderDialog() await clickAddCredits() @@ -807,9 +810,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(mockBillingContext().topup).mockResolvedValue( + topupResponse('completed') + ) + vi.mocked(mockBillingContext().fetchBalance).mockRejectedValueOnce( + new Error('balance unavailable') + ) + vi.mocked(mockBillingContext().fetchStatus).mockRejectedValueOnce( + new Error('status unavailable') + ) renderDialog() await clickAddCredits() @@ -827,7 +836,9 @@ describe('TopUpCreditsDialogContentWorkspace', () => { }) it('does not refresh balance or status for a pending top-up', async () => { - mockTopup.mockResolvedValue(topupResponse('pending')) + vi.mocked(mockBillingContext().topup).mockResolvedValue( + topupResponse('pending') + ) renderDialog() await clickAddCredits() @@ -841,22 +852,24 @@ describe('TopUpCreditsDialogContentWorkspace', () => { autoHandleRequiresAction: true } ) - expect(mockFetchBalance).not.toHaveBeenCalled() - expect(mockFetchStatus).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 () => { - mockTopup.mockResolvedValue(topupResponse('failed')) + vi.mocked(mockBillingContext().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(mockBillingContext().fetchBalance).not.toHaveBeenCalled() + expect(mockBillingContext().fetchStatus).not.toHaveBeenCalled() expect(useTelemetry()?.trackBillingEvent).toHaveBeenCalledWith({ operation: 'topup', stage: 'failed', @@ -878,7 +891,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(mockBillingContext().topup).mockRejectedValue(workspaceApiError) renderDialog() await clickAddCredits() @@ -903,7 +916,7 @@ describe('TopUpCreditsDialogContentWorkspace', () => { expect(screen.getByRole('button', { name: 'Pay $50.00' })).toBeDisabled() - expect(mockTopup).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 8029b40d6d4..704c38972d3 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,13 @@ function inviteButton() { } beforeEach(() => { + const billing = useBillingContext() + Object.assign(billing, { + maxSeats: computed(() => mockMaxSeats.value), + occupiedSeats: computed(() => mockOccupiedSeats.value) + }) + vi.mocked(useBillingContext).mockReturnValue(billing) + Object.assign(useTeamWorkspaceStore(), { pendingInvites: [] }) vi.mocked(useDialogStore().closeDialog).mockImplementation(() => {}) }) @@ -83,7 +79,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..69e23f4b650 100644 --- a/src/platform/workspace/composables/useResubscribe.test.ts +++ b/src/platform/workspace/composables/useResubscribe.test.ts @@ -6,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' @@ -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: () => ({ @@ -79,6 +77,7 @@ vi.mock( const apps: App[] = [] function useResubscribe(): ReturnType { + mockBillingContext() let result: ReturnType | undefined const app = createApp( defineComponent({ @@ -105,7 +104,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 +114,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).not.toHaveBeenCalled() + expect(mockBillingContext().resubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackResubscribeClicked).not.toHaveBeenCalled() expect(state.toastAdd).not.toHaveBeenCalled() expect(isResubscribing.value).toBe(false) @@ -130,7 +128,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).not.toHaveBeenCalled() + expect(mockBillingContext().resubscribe).not.toHaveBeenCalled() expect(useTelemetry()?.trackResubscribeClicked).not.toHaveBeenCalled() expect(state.toastAdd).not.toHaveBeenCalled() expect(isResubscribing.value).toBe(false) @@ -146,7 +144,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).toHaveBeenCalled() + expect(mockBillingContext().resubscribe).toHaveBeenCalled() }) it('refuses whenever the policy denies it', async () => { @@ -158,7 +156,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).not.toHaveBeenCalled() + expect(mockBillingContext().resubscribe).not.toHaveBeenCalled() }) it('fires a started event before resubscribe resolves', async () => { @@ -184,7 +182,7 @@ describe('useResubscribe', () => { await handleResubscribe() - expect(state.resubscribe).toHaveBeenCalledOnce() + expect(mockBillingContext().resubscribe).toHaveBeenCalledOnce() expect(useTelemetry()?.trackResubscribeClicked).toHaveBeenCalledOnce() expect(useTelemetry()?.trackBillingEvent).not.toHaveBeenCalledWith( expect.objectContaining({ stage: 'succeeded' }) @@ -204,14 +202,14 @@ describe('useResubscribe', () => { }) it('shows an error and resets loading when resubscription fails', async () => { - state.resubscribe.mockRejectedValueOnce( + vi.mocked(mockBillingContext().resubscribe).mockRejectedValueOnce( new Error('Resubscribe failed for person@example.com') ) const { handleResubscribe, isResubscribing } = useResubscribe() await handleResubscribe() - expect(state.resubscribe).toHaveBeenCalledOnce() + expect(mockBillingContext().resubscribe).toHaveBeenCalledOnce() expect(state.toastAdd).toHaveBeenCalledWith( expect.objectContaining({ severity: 'error', @@ -234,7 +232,9 @@ describe('useResubscribe', () => { 'checkout initiation rejected', 500 ) - state.resubscribe.mockRejectedValueOnce(authStoreError) + vi.mocked(mockBillingContext().resubscribe).mockRejectedValueOnce( + authStoreError + ) const { handleResubscribe } = useResubscribe() await handleResubscribe() @@ -254,7 +254,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(mockBillingContext().resubscribe).mockRejectedValueOnce( + authStoreError + ) const { handleResubscribe } = useResubscribe() await handleResubscribe() @@ -270,7 +272,7 @@ describe('useResubscribe', () => { it('emits started before the awaited resubscribe call resolves', async () => { const callOrder: string[] = [] - state.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 156378e70c2..4ec360b34c5 100644 --- a/src/platform/workspace/stores/billingOperationStore.test.ts +++ b/src/platform/workspace/stores/billingOperationStore.test.ts @@ -12,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( () => ({ @@ -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'), @@ -459,6 +451,7 @@ describe('billingOperationStore', () => { }) it('updates status and shows toast on success', async () => { + const billing = mockBillingContext() vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', @@ -475,9 +468,9 @@ describe('billingOperationStore', () => { expect(store.hasPendingOperations).toBe(false) expect(mockRefreshCapabilities).toHaveBeenCalledOnce() - expect(mockReconcileSubscriptionSuccess).toHaveBeenCalledOnce() - expect(mockFetchStatus).not.toHaveBeenCalled() - expect(mockFetchBalance).not.toHaveBeenCalled() + expect(billing.reconcileSubscriptionSuccess).toHaveBeenCalledOnce() + expect(billing.fetchStatus).not.toHaveBeenCalled() + expect(billing.fetchBalance).not.toHaveBeenCalled() expect(useToastStore().add).toHaveBeenCalledWith({ severity: 'success', @@ -886,14 +879,17 @@ describe('billingOperationStore', () => { }) it('resolves the terminal promise even if reconciliation throws synchronously', async () => { + const billing = mockBillingContext() vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', started_at: new Date().toISOString() }) - mockReconcileSubscriptionSuccess.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') @@ -2460,6 +2456,7 @@ describe('billingOperationStore', () => { }) it('resolves with the succeeded operation and refreshes status', async () => { + const billing = mockBillingContext() vi.mocked(workspaceApi.getBillingOpStatus).mockResolvedValue({ id: 'op-1', status: 'succeeded', @@ -2473,7 +2470,7 @@ describe('billingOperationStore', () => { const operation = await terminal expect(operation.status).toBe('succeeded') - expect(mockFetchStatus).toHaveBeenCalled() + expect(billing.fetchStatus).toHaveBeenCalled() expect( useTeamWorkspaceStore().updateActiveWorkspace ).toHaveBeenCalledWith({ @@ -2490,7 +2487,10 @@ describe('billingOperationStore', () => { }) it('resolves the terminal outcome even when the post-success refresh fails', async () => { - mockFetchStatus.mockRejectedValueOnce(new Error('refresh failed')) + const billing = mockBillingContext() + vi.mocked(billing.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..b8e3dfa2446 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,10 @@ function mountRunButton( } beforeEach(() => { + const billing = useBillingContext() + billing.canRunWorkflows = computed(() => mocks.canRunWorkflows.value) + vi.mocked(useBillingContext).mockReturnValue(billing) + Object.assign(useOnboardingTourStore(), { activeTour: ref['activeTour']>(null), @@ -995,7 +994,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..6b464b19a88 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,9 @@ function renderControls({ canRunWorkflows?: boolean mobile?: boolean } = {}) { - billingMock.canRunWorkflows = canRunWorkflows + const billing = useBillingContext() + billing.canRunWorkflows = computed(() => canRunWorkflows) + vi.mocked(useBillingContext).mockReturnValue(billing) const pinia = getActivePinia()! @@ -163,7 +158,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..bea6070eb7c 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,21 @@ vi.mock(import('@/i18n'), () => ({ vi.mock(import('@/platform/telemetry')) +beforeEach(() => { + const billing = useBillingContext() + Object.assign(billing, { + canAccessSubscriptionFeatures: computed(() => true), + isFreeTier: computed(() => false), + type: computed(() => 'legacy') + }) + vi.mocked(useBillingContext).mockReturnValue(billing) +}) + 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..728dc47bb1c 100644 --- a/src/services/dialogService.renderer.test.ts +++ b/src/services/dialogService.renderer.test.ts @@ -1,9 +1,11 @@ +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'`. * 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 @@ -11,18 +13,22 @@ vi.mock(import('@/i18n'), () => ({ vi.mock(import('@/platform/telemetry')) +beforeEach(() => { + const billing = useBillingContext() + Object.assign(billing, { + canAccessSubscriptionFeatures: computed(() => true), + isTeamPlan: computed(() => false), + tier: computed(() => 'STANDARD'), + type: computed(() => 'legacy') + }) + vi.mocked(useBillingContext).mockReturnValue(billing) +}) + 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'), 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 +}