From f0a78b83c2c0ccc8e2d4c3610295183050f2b9b5 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Sat, 3 Oct 2026 00:54:05 +0000 Subject: [PATCH 1/7] test: flag redundant per-mock cleanup in Vitest hooks Amp-Thread-ID: https://ampcode.com/threads/T-01a0fedc-ff89-70cb-a069-0b7f4feb4985 --- apps/billing-web/src/config/firebase.test.ts | 4 -- .../src/session/stripeChallengePort.test.ts | 8 --- .../src/config/workshop-firebase.test.ts | 6 +- apps/website/src/utils/ashby.ci.test.ts | 1 - apps/website/src/utils/cloudNodes.ci.test.ts | 1 - .../website/src/utils/featureFlags.ci.test.ts | 1 - .../helpcenter/HelpCenterMenuContent.test.ts | 10 +-- src/components/load3d/modelThumbnail.test.ts | 4 +- .../errors/useErrorActions.test.ts | 6 +- .../errors/useErrorReport.test.ts | 6 +- src/composables/useFeatureFlags.test.ts | 1 - src/composables/useLoad3dViewer.test.ts | 3 +- .../preview/previewExposureChain.test.ts | 6 +- src/extensions/core/groupOptions.test.ts | 1 - .../litegraph/src/LGraph.serialise.test.ts | 6 +- src/lib/litegraph/src/graphIntents.test.ts | 1 - .../litegraph/src/node/NodeInputSlot.test.ts | 1 - .../litegraph/src/node/NodeOutputSlot.test.ts | 1 - .../composables/useUploadModelWizard.test.ts | 1 - .../cloud/oauth/OAuthConsentView.test.ts | 2 +- .../oauth/useOAuthPostLoginRedirect.test.ts | 2 +- .../onboarding/onboardingCloudRoutes.test.ts | 1 - .../components/SubscribeButton.test.ts | 6 +- .../composables/useSubscription.test.ts | 1 - .../utils/subscriptionCheckoutUtil.test.ts | 1 - ...ingService.registerUserKeybindings.test.ts | 6 +- ...onboardingTourStore.registeredTour.test.ts | 1 - .../onboarding/onboardingTourStore.test.ts | 1 - .../telemetry/assertFailureReporter.test.ts | 6 +- .../telemetry/assetLoadErrorReporting.test.ts | 1 - src/platform/telemetry/perf/perfMark.test.ts | 6 +- .../cloud/storeReadinessGate.test.ts | 1 - .../stores/workflowDraftStoreV2.test.ts | 1 - .../billing/openHostedBillingTab.test.ts | 8 +-- .../useDowngradeToPersonal.test.ts | 6 +- .../useSubscriptionCheckout.test.ts | 9 +-- .../firstRunTour/tour/cameraFraming.test.ts | 2 - .../tour/canvasCoachTarget.test.ts | 2 - .../components/WidgetRecordAudio.test.ts | 7 +- src/services/customerEventsService.test.ts | 1 - .../gateway/registrySearchGateway.test.ts | 14 +--- src/stores/assetsStore.test.ts | 8 +-- src/stores/workspace/sidebarTabStore.test.ts | 1 - .../agent/message/ReplyAssetGroup.test.ts | 8 +-- .../agent/message/ReplyAudioCard.test.ts | 4 +- .../extensions/agent/crdt/docOpMinter.test.ts | 1 - .../services/agent/agentRestClient.test.ts | 6 +- tools/oxlint-plugins/vitestCleanup.test.ts | 48 ++++++++++++- tools/oxlint-plugins/vitestCleanup.ts | 70 +++++++++++++++++++ tools/test-recorder/src/pr/gh.test.ts | 1 - 50 files changed, 146 insertions(+), 154 deletions(-) diff --git a/apps/billing-web/src/config/firebase.test.ts b/apps/billing-web/src/config/firebase.test.ts index fb589ddd302..dd47f92ea4f 100644 --- a/apps/billing-web/src/config/firebase.test.ts +++ b/apps/billing-web/src/config/firebase.test.ts @@ -25,10 +25,6 @@ const testIdentity = createTestIdentity({ onUserChanged: () => () => undefined }) as unknown as FirebaseIdentity -beforeEach(() => { - h.resolveFirebaseIdentity.mockReset() -}) - async function freshFirebase() { vi.resetModules() return import('@/config/firebase') diff --git a/apps/billing-web/src/session/stripeChallengePort.test.ts b/apps/billing-web/src/session/stripeChallengePort.test.ts index 976eb84a561..742aa6b5ab7 100644 --- a/apps/billing-web/src/session/stripeChallengePort.test.ts +++ b/apps/billing-web/src/session/stripeChallengePort.test.ts @@ -9,10 +9,6 @@ vi.mock(import('@stripe/stripe-js/pure'), () => ({ import { createDeferredStripeChallengePort } from '@/session/stripeChallengePort' describe('createDeferredStripeChallengePort', () => { - beforeEach(() => { - h.loadStripe.mockReset() - }) - it('reports the challenge unavailable when no key is present at call time', async () => { const port = createDeferredStripeChallengePort(() => undefined) @@ -106,10 +102,6 @@ describe('createDeferredStripeChallengePort', () => { }) describe('leavesPage', () => { - beforeEach(() => { - h.loadStripe.mockReset() - }) - it.for<{ name: string; retrieved: unknown; leaves: boolean }>([ { name: 'a challenge Stripe runs in the page', diff --git a/apps/website/src/config/workshop-firebase.test.ts b/apps/website/src/config/workshop-firebase.test.ts index 44f039a1eb8..de371cdc511 100644 --- a/apps/website/src/config/workshop-firebase.test.ts +++ b/apps/website/src/config/workshop-firebase.test.ts @@ -1,5 +1,5 @@ import type { UserCredential } from 'firebase/auth' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { captureSignupRollbackFailure } from '../scripts/posthog' import { @@ -163,10 +163,6 @@ describe('popup sign-in', () => { describe('social sign-in provisioning boundary', () => { const user = { uid: 'u1', email: 'a@b.co', getIdToken: async () => 'jwt' } - beforeEach(() => { - h.signInWithGoogle.mockReset() - }) - it('rethrows a popup failure untouched, so the caller sees the Firebase code', async () => { const popupFailure = { code: 'auth/popup-closed-by-user', message: 'x' } h.signInWithGoogle.mockRejectedValue(popupFailure) diff --git a/apps/website/src/utils/ashby.ci.test.ts b/apps/website/src/utils/ashby.ci.test.ts index 7d10a713079..8047369c2a0 100644 --- a/apps/website/src/utils/ashby.ci.test.ts +++ b/apps/website/src/utils/ashby.ci.test.ts @@ -75,7 +75,6 @@ describe('reportAshbyOutcome', () => { }) afterEach(() => { - writeSpy.mockRestore() rmSync(summaryDir, { recursive: true, force: true }) if (originalSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY else process.env.GITHUB_STEP_SUMMARY = originalSummary diff --git a/apps/website/src/utils/cloudNodes.ci.test.ts b/apps/website/src/utils/cloudNodes.ci.test.ts index eca5599b5a6..23e0261ed75 100644 --- a/apps/website/src/utils/cloudNodes.ci.test.ts +++ b/apps/website/src/utils/cloudNodes.ci.test.ts @@ -59,7 +59,6 @@ describe('reportCloudNodesOutcome', () => { }) afterEach(() => { - writeSpy.mockRestore() rmSync(summaryDir, { recursive: true, force: true }) if (originalSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY else process.env.GITHUB_STEP_SUMMARY = originalSummary diff --git a/apps/website/src/utils/featureFlags.ci.test.ts b/apps/website/src/utils/featureFlags.ci.test.ts index 4b8c40f509e..55a0cd2b158 100644 --- a/apps/website/src/utils/featureFlags.ci.test.ts +++ b/apps/website/src/utils/featureFlags.ci.test.ts @@ -39,7 +39,6 @@ describe('reportFeatureFlagsOutcome', () => { }) afterEach(() => { - writeSpy.mockRestore() rmSync(summaryDir, { recursive: true, force: true }) if (originalSummary === undefined) delete process.env.GITHUB_STEP_SUMMARY else process.env.GITHUB_STEP_SUMMARY = originalSummary diff --git a/src/components/helpcenter/HelpCenterMenuContent.test.ts b/src/components/helpcenter/HelpCenterMenuContent.test.ts index 6535a4fa03f..4fdc7395adc 100644 --- a/src/components/helpcenter/HelpCenterMenuContent.test.ts +++ b/src/components/helpcenter/HelpCenterMenuContent.test.ts @@ -1,7 +1,7 @@ import userEvent from '@testing-library/user-event' import { render, screen, waitFor } from '@testing-library/vue' import axios from 'axios' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { computed, defineComponent, h } from 'vue' import { createI18n } from 'vue-i18n' @@ -102,10 +102,6 @@ describe('HelpCenterMenuContent feedback item', () => { openSpy = vi.spyOn(window, 'open').mockReturnValue(null) }) - afterEach(() => { - openSpy.mockRestore() - }) - it('opens the Typeform survey tagged with help-center source on Cloud', async () => { distribution.isCloud = true const { user } = renderComponent() @@ -156,10 +152,6 @@ describe('HelpCenterMenuContent system status item', () => { openSpy = vi.spyOn(window, 'open').mockReturnValue(null) }) - afterEach(() => { - openSpy.mockRestore() - }) - it('opens the status page on Cloud', async () => { distribution.isCloud = true const { user } = renderComponent() diff --git a/src/components/load3d/modelThumbnail.test.ts b/src/components/load3d/modelThumbnail.test.ts index da51e12f5c6..79e19ee4c8b 100644 --- a/src/components/load3d/modelThumbnail.test.ts +++ b/src/components/load3d/modelThumbnail.test.ts @@ -25,9 +25,7 @@ function mockInstance(overrides: Record = {}) { describe('generateModelThumbnail', () => { beforeEach(() => { - createLoad3d.mockReset() - isAssetPreviewSupported.mockReset().mockReturnValue(false) - persistThumbnail.mockReset() + isAssetPreviewSupported.mockReturnValue(false) }) it('renders offscreen, returns the data url, and disposes the instance', async () => { diff --git a/src/components/rightSidePanel/errors/useErrorActions.test.ts b/src/components/rightSidePanel/errors/useErrorActions.test.ts index 3bc36935413..bba584c5318 100644 --- a/src/components/rightSidePanel/errors/useErrorActions.test.ts +++ b/src/components/rightSidePanel/errors/useErrorActions.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { useCommandStore } from '@/stores/commandStore' @@ -32,10 +32,6 @@ describe('useErrorActions', () => { windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null) }) - afterEach(() => { - windowOpenSpy.mockRestore() - }) - describe('openGitHubIssues', () => { it('tracks the button click and opens the GitHub issues URL in a new tab', () => { const { openGitHubIssues } = useErrorActions() diff --git a/src/components/rightSidePanel/errors/useErrorReport.test.ts b/src/components/rightSidePanel/errors/useErrorReport.test.ts index 76d937cfb30..babeb18b4d6 100644 --- a/src/components/rightSidePanel/errors/useErrorReport.test.ts +++ b/src/components/rightSidePanel/errors/useErrorReport.test.ts @@ -1,5 +1,5 @@ import { until } from '@vueuse/core' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick, ref } from 'vue' import { useSystemStatsStore } from '@/stores/systemStatsStore' @@ -73,10 +73,6 @@ describe('useErrorReport', () => { warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) }) - afterEach(() => { - warnSpy.mockRestore() - }) - it('returns early without enrichment when the card has no runtime errors', async () => { const card = makeCard({ errors: [{ message: 'static', details: 'details' }] diff --git a/src/composables/useFeatureFlags.test.ts b/src/composables/useFeatureFlags.test.ts index 2180c121010..71fd4f5095b 100644 --- a/src/composables/useFeatureFlags.test.ts +++ b/src/composables/useFeatureFlags.test.ts @@ -1095,7 +1095,6 @@ describe('useFeatureFlags', () => { describe('session override precedence', () => { afterEach(() => { - vi.mocked(getSessionOverride).mockReset() vi.mocked(distributionTypes).isCloud = false vi.mocked(distributionTypes).isNightly = false remoteConfigState.value = 'unloaded' diff --git a/src/composables/useLoad3dViewer.test.ts b/src/composables/useLoad3dViewer.test.ts index be6c1b24b6c..06f79bf89ca 100644 --- a/src/composables/useLoad3dViewer.test.ts +++ b/src/composables/useLoad3dViewer.test.ts @@ -772,8 +772,7 @@ describe('useLoad3dViewer', () => { describe('standalone thumbnail persistence', () => { beforeEach(() => { - isAssetPreviewSupported.mockReset().mockReturnValue(false) - persistThumbnail.mockReset() + isAssetPreviewSupported.mockReturnValue(false) vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue({ blob: () => Promise.resolve(new Blob()) }) diff --git a/src/core/graph/subgraph/preview/previewExposureChain.test.ts b/src/core/graph/subgraph/preview/previewExposureChain.test.ts index 42704bd966d..e729a272cf6 100644 --- a/src/core/graph/subgraph/preview/previewExposureChain.test.ts +++ b/src/core/graph/subgraph/preview/previewExposureChain.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import type { PreviewExposure } from '@/core/schemas/previewExposureSchema' import { toNodeId } from '@/types/nodeId' @@ -50,10 +50,6 @@ describe(resolvePreviewExposureChain, () => { warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) }) - afterEach(() => { - warnSpy.mockRestore() - }) - it('returns undefined when the named exposure is not on the starting host', () => { const ctx = makeContext(new Map(), []) expect( diff --git a/src/extensions/core/groupOptions.test.ts b/src/extensions/core/groupOptions.test.ts index 8931ee23c83..1b4f8c3cd6d 100644 --- a/src/extensions/core/groupOptions.test.ts +++ b/src/extensions/core/groupOptions.test.ts @@ -73,7 +73,6 @@ const BASE_GROUP_ITEMS: (string | null)[] = [ ] beforeEach(() => { - graphChange.mockClear() vi.mocked(useSettingStore().get).mockReturnValue(10) }) diff --git a/src/lib/litegraph/src/LGraph.serialise.test.ts b/src/lib/litegraph/src/LGraph.serialise.test.ts index bc35569428f..39b4d6d0cef 100644 --- a/src/lib/litegraph/src/LGraph.serialise.test.ts +++ b/src/lib/litegraph/src/LGraph.serialise.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe } from 'vitest' +import { describe } from 'vitest' import { LGraph, @@ -18,10 +18,6 @@ vi.mock(import('@/platform/telemetry/reportError'), () => ({ reportError: mockReportError })) -beforeEach(() => { - mockReportError.mockClear() -}) - describe('LGraph Serialisation', () => { test('can (de)serialise node / group titles', ({ expect, minimalGraph }) => { const nodeTitle = 'Test Node' diff --git a/src/lib/litegraph/src/graphIntents.test.ts b/src/lib/litegraph/src/graphIntents.test.ts index 0d6f94049d6..92faa6bc17d 100644 --- a/src/lib/litegraph/src/graphIntents.test.ts +++ b/src/lib/litegraph/src/graphIntents.test.ts @@ -32,7 +32,6 @@ function track(detach: () => void): void { afterEach(() => { for (const detach of detachers.splice(0)) detach() - vi.mocked(reportError).mockClear() }) describe('withGraphIntentSource', () => { diff --git a/src/lib/litegraph/src/node/NodeInputSlot.test.ts b/src/lib/litegraph/src/node/NodeInputSlot.test.ts index c58f8266afa..259467e3730 100644 --- a/src/lib/litegraph/src/node/NodeInputSlot.test.ts +++ b/src/lib/litegraph/src/node/NodeInputSlot.test.ts @@ -30,7 +30,6 @@ describe('NodeInputSlot', () => { const originalCallbacks = LiteGraph.onDeprecationWarning beforeEach(() => { - onWarning.mockClear() LiteGraph.onDeprecationWarning = [onWarning] LiteGraph.alwaysRepeatWarnings = true }) diff --git a/src/lib/litegraph/src/node/NodeOutputSlot.test.ts b/src/lib/litegraph/src/node/NodeOutputSlot.test.ts index ee4c94f189a..7e9989331f2 100644 --- a/src/lib/litegraph/src/node/NodeOutputSlot.test.ts +++ b/src/lib/litegraph/src/node/NodeOutputSlot.test.ts @@ -22,7 +22,6 @@ describe('NodeOutputSlot deprecated links getter', () => { const onWarning = vi.fn() beforeEach(() => { - onWarning.mockClear() LiteGraph.onDeprecationWarning = [onWarning] LiteGraph.alwaysRepeatWarnings = true }) diff --git a/src/platform/assets/composables/useUploadModelWizard.test.ts b/src/platform/assets/composables/useUploadModelWizard.test.ts index 0861e3280e7..f7b7b55b187 100644 --- a/src/platform/assets/composables/useUploadModelWizard.test.ts +++ b/src/platform/assets/composables/useUploadModelWizard.test.ts @@ -95,7 +95,6 @@ describe('useUploadModelWizard', () => { } afterEach(() => { - vi.mocked(api.getServerFeature).mockReset() for (const app of mountedApps.splice(0)) { app.unmount() } diff --git a/src/platform/cloud/oauth/OAuthConsentView.test.ts b/src/platform/cloud/oauth/OAuthConsentView.test.ts index 93e02007045..83e49075009 100644 --- a/src/platform/cloud/oauth/OAuthConsentView.test.ts +++ b/src/platform/cloud/oauth/OAuthConsentView.test.ts @@ -96,7 +96,7 @@ const renderConsent = (overrides: Partial = {}) => describe('OAuthConsentView', () => { beforeEach(() => { - mockSubmitOAuthConsentDecision.mockReset().mockResolvedValue(undefined) + mockSubmitOAuthConsentDecision.mockResolvedValue(undefined) }) it('shows the generic app icon regardless of client_display_name', () => { diff --git a/src/platform/cloud/oauth/useOAuthPostLoginRedirect.test.ts b/src/platform/cloud/oauth/useOAuthPostLoginRedirect.test.ts index b1408f2d91c..a14b73011a4 100644 --- a/src/platform/cloud/oauth/useOAuthPostLoginRedirect.test.ts +++ b/src/platform/cloud/oauth/useOAuthPostLoginRedirect.test.ts @@ -44,7 +44,7 @@ function mountRedirect() { describe('useOAuthPostLoginRedirect', () => { beforeEach(() => { - createSessionOrThrow.mockReset().mockResolvedValue(undefined) + createSessionOrThrow.mockResolvedValue(undefined) }) it('returns no-oauth when neither query nor sessionStorage holds a request id', async () => { diff --git a/src/platform/cloud/onboarding/onboardingCloudRoutes.test.ts b/src/platform/cloud/onboarding/onboardingCloudRoutes.test.ts index cbae2cb6f26..b81033d7542 100644 --- a/src/platform/cloud/onboarding/onboardingCloudRoutes.test.ts +++ b/src/platform/cloud/onboarding/onboardingCloudRoutes.test.ts @@ -196,7 +196,6 @@ describe('cloudOnboardingRoutes', () => { */ describe('legacy /login through the cloud-login guard', () => { beforeEach(() => { - vi.mocked(useCurrentUser).mockClear() clearOAuthRequestId() }) diff --git a/src/platform/cloud/subscription/components/SubscribeButton.test.ts b/src/platform/cloud/subscription/components/SubscribeButton.test.ts index c22f1ac44f6..b654efbe470 100644 --- a/src/platform/cloud/subscription/components/SubscribeButton.test.ts +++ b/src/platform/cloud/subscription/components/SubscribeButton.test.ts @@ -1,6 +1,6 @@ import { useBillingContext } from '@/composables/billing/useBillingContext' import { getActivePinia } from 'pinia' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { computed } from 'vue' import { createI18n } from 'vue-i18n' @@ -37,10 +37,6 @@ function renderComponent() { } describe('SubscribeButton', () => { - beforeEach(() => { - vi.mocked(useTelemetry())!.trackSubscription.mockClear() - }) - it('names its own surface on the subscribe event', async () => { renderComponent() diff --git a/src/platform/cloud/subscription/composables/useSubscription.test.ts b/src/platform/cloud/subscription/composables/useSubscription.test.ts index ac892650373..8878441bedc 100644 --- a/src/platform/cloud/subscription/composables/useSubscription.test.ts +++ b/src/platform/cloud/subscription/composables/useSubscription.test.ts @@ -221,7 +221,6 @@ const statusReadPaths = [ global.fetch = vi.fn() beforeEach(() => { - vi.mocked(webSessionResourceHeader).mockReset() vi.mocked(webSessionResourceHeader).mockResolvedValue(undefined) useErrorHandling().wrapWithErrorHandlingAsync = (action, errorHandler) => diff --git a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts index cf9b94c0632..678408c428b 100644 --- a/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts +++ b/src/platform/cloud/subscription/utils/subscriptionCheckoutUtil.test.ts @@ -96,7 +96,6 @@ function createDeferred() { } beforeEach(() => { - vi.mocked(webSessionResourceHeader).mockReset() vi.mocked(webSessionResourceHeader).mockResolvedValue(undefined) Object.assign(useAuthStore(), { userId: 'user-123' }) vi.mocked(useAuthStore().getFirebaseAuthHeader).mockResolvedValue({ diff --git a/src/platform/keybindings/keybindingService.registerUserKeybindings.test.ts b/src/platform/keybindings/keybindingService.registerUserKeybindings.test.ts index fbdbc7de928..9a5ba257a4e 100644 --- a/src/platform/keybindings/keybindingService.registerUserKeybindings.test.ts +++ b/src/platform/keybindings/keybindingService.registerUserKeybindings.test.ts @@ -1,5 +1,5 @@ import { useSettingStore } from '@/platform/settings/settingStore' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { KeybindingImpl } from '@/platform/keybindings/keybinding' import { useKeybindingService } from '@/platform/keybindings/keybindingService' @@ -15,10 +15,6 @@ describe('keybindingService - registerUserKeybindings', () => { warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) }) - afterEach(() => { - warnSpy.mockRestore() - }) - it('does not warn when unset binding targets a command that no longer exists', () => { // A command removed from the app (e.g. ConvertSelectedNodesToGroupNode, // removed in #12931) can still linger in the persisted UnsetBindings. diff --git a/src/platform/onboarding/onboardingTourStore.registeredTour.test.ts b/src/platform/onboarding/onboardingTourStore.registeredTour.test.ts index 4c4cee3ed1c..9be50b8eb53 100644 --- a/src/platform/onboarding/onboardingTourStore.registeredTour.test.ts +++ b/src/platform/onboarding/onboardingTourStore.registeredTour.test.ts @@ -51,7 +51,6 @@ beforeEach(() => { describe('onboardingTourStore — runtime-resolved tours', () => { afterEach(() => { clearCoachmarks() - trackOnboardingTour.mockClear() }) it('reports no start for an entry no one registered', async () => { diff --git a/src/platform/onboarding/onboardingTourStore.test.ts b/src/platform/onboarding/onboardingTourStore.test.ts index 724ed99baa6..9a5754805ef 100644 --- a/src/platform/onboarding/onboardingTourStore.test.ts +++ b/src/platform/onboarding/onboardingTourStore.test.ts @@ -101,7 +101,6 @@ describe('onboardingTourStore', () => { appendedTargets.forEach((el) => el.remove()) appendedTargets.length = 0 setViewport({ width: 1024, height: 768 }) - trackOnboardingTour.mockClear() }) /** Register one laid-out element for a coach id, so its step resolves at once. */ diff --git a/src/platform/telemetry/assertFailureReporter.test.ts b/src/platform/telemetry/assertFailureReporter.test.ts index a7ff14f9924..057aa347916 100644 --- a/src/platform/telemetry/assertFailureReporter.test.ts +++ b/src/platform/telemetry/assertFailureReporter.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' const mockReportError = vi.hoisted(() => vi.fn()) vi.mock(import('./reportError'), () => ({ @@ -11,10 +11,6 @@ async function loadReporter() { } describe('reportAssertFailure', () => { - beforeEach(() => { - mockReportError.mockClear() - }) - it('reports an assertion failure as an invariant error', async () => { const reportAssertFailure = await loadReporter() diff --git a/src/platform/telemetry/assetLoadErrorReporting.test.ts b/src/platform/telemetry/assetLoadErrorReporting.test.ts index a3624201d84..3777f5e527b 100644 --- a/src/platform/telemetry/assetLoadErrorReporting.test.ts +++ b/src/platform/telemetry/assetLoadErrorReporting.test.ts @@ -15,7 +15,6 @@ describe('asset load error reporting', () => { let consoleError: MockInstance beforeEach(() => { - mockReportError.mockClear() consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) }) diff --git a/src/platform/telemetry/perf/perfMark.test.ts b/src/platform/telemetry/perf/perfMark.test.ts index 92204785c8b..d194ff5da57 100644 --- a/src/platform/telemetry/perf/perfMark.test.ts +++ b/src/platform/telemetry/perf/perfMark.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { perfMark, perfPoint } from './perfMark' @@ -7,10 +7,6 @@ const { addBreadcrumb } = vi.hoisted(() => ({ addBreadcrumb: vi.fn() })) vi.mock(import('@sentry/vue'), () => ({ addBreadcrumb })) describe('perfMark', () => { - beforeEach(() => { - addBreadcrumb.mockReset() - }) - it('degrades to no-op tracing without the Performance API', async () => { vi.stubGlobal('performance', undefined) diff --git a/src/platform/telemetry/providers/cloud/storeReadinessGate.test.ts b/src/platform/telemetry/providers/cloud/storeReadinessGate.test.ts index 9f0ff780cd6..56517f855f3 100644 --- a/src/platform/telemetry/providers/cloud/storeReadinessGate.test.ts +++ b/src/platform/telemetry/providers/cloud/storeReadinessGate.test.ts @@ -119,7 +119,6 @@ describe('telemetry providers wait for Pinia before touching stores', () => { afterEach(() => { markStoresReady() hoisted.customerIoRegistration.rejection = null - hoisted.reportError.mockClear() delete (window as { __CONFIG__?: unknown }).__CONFIG__ }) diff --git a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.test.ts b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.test.ts index 2a14f2adedc..4fa5b76b4cd 100644 --- a/src/platform/workflow/persistence/stores/workflowDraftStoreV2.test.ts +++ b/src/platform/workflow/persistence/stores/workflowDraftStoreV2.test.ts @@ -71,7 +71,6 @@ describe('workflowDraftStoreV2', () => { }) afterEach(() => { - activeSpy?.mockRestore() activeSpy = null localStorage.clear() sessionStorage.clear() diff --git a/src/platform/workspace/billing/openHostedBillingTab.test.ts b/src/platform/workspace/billing/openHostedBillingTab.test.ts index 9e88f6c098e..b9afe43ad75 100644 --- a/src/platform/workspace/billing/openHostedBillingTab.test.ts +++ b/src/platform/workspace/billing/openHostedBillingTab.test.ts @@ -61,12 +61,8 @@ function fakeTab(): Window { describe('openHostedBillingTab', () => { beforeEach(() => { - mockHostedBillingRoute.mockReset().mockReturnValue(BILLING_WEB_ROUTE) - mockFetchStatus.mockClear() - mockFetchBalance.mockClear() - mockCapabilitiesRefresh.mockClear() - mockStop.mockClear() - mockRegisterRefreshOnReturn.mockClear().mockReturnValue(mockStop) + mockHostedBillingRoute.mockReturnValue(BILLING_WEB_ROUTE) + mockRegisterRefreshOnReturn.mockReturnValue(mockStop) flagState.hostedBillingDestination = 'billing_web' Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-123' }) }) diff --git a/src/platform/workspace/composables/useDowngradeToPersonal.test.ts b/src/platform/workspace/composables/useDowngradeToPersonal.test.ts index 9f23be3116a..cfafecc9fab 100644 --- a/src/platform/workspace/composables/useDowngradeToPersonal.test.ts +++ b/src/platform/workspace/composables/useDowngradeToPersonal.test.ts @@ -1,7 +1,7 @@ import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' import { getActivePinia } from 'pinia' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { computed, ref } from 'vue' import { useCurrentUser } from '@/composables/auth/useCurrentUser' @@ -172,10 +172,6 @@ describe('useDowngradeToPersonal', () => { windowOpen = vi.spyOn(window, 'open').mockReturnValue({} as Window) }) - afterEach(() => { - windowOpen.mockRestore() - }) - describe('removableMembers / hasOtherMembers', () => { it('protects only the original owner, removing promoted owners and members', () => { mockMembers.value = [ diff --git a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts index 9c4480e3f20..a09eebcaf0e 100644 --- a/src/platform/workspace/composables/useSubscriptionCheckout.test.ts +++ b/src/platform/workspace/composables/useSubscriptionCheckout.test.ts @@ -553,13 +553,8 @@ describe('useSubscriptionCheckout', () => { } beforeEach(() => { - mockSubscribe.mockReset() - mockPreviewSubscribe.mockReset() - mockFetchPlans.mockReset() - mockFetchStatus.mockReset().mockResolvedValue(undefined) - vi.mocked(useBillingOperationStore().startOperation).mockReset() - mockListSavedPaymentMethods.mockReset() - mockOpenHostedBillingTab.mockReset().mockReturnValue(false) + mockFetchStatus.mockResolvedValue(undefined) + mockOpenHostedBillingTab.mockReturnValue(false) railState.rail = null Object.assign(useBillingOperationStore(), { subscriptionActionOperation: undefined diff --git a/src/renderer/extensions/firstRunTour/tour/cameraFraming.test.ts b/src/renderer/extensions/firstRunTour/tour/cameraFraming.test.ts index 1ed0a4723e8..ff38de3880e 100644 --- a/src/renderer/extensions/firstRunTour/tour/cameraFraming.test.ts +++ b/src/renderer/extensions/firstRunTour/tour/cameraFraming.test.ts @@ -149,8 +149,6 @@ describe('frameNode', () => { afterEach(() => { endRunningSteps() - camera.animateToBounds.mockClear() - camera.ds.fitToBounds.mockClear() camera.ds.offset = [0, 0] camera.ds.scale = 1 useCanvasStore().canvas = null diff --git a/src/renderer/extensions/firstRunTour/tour/canvasCoachTarget.test.ts b/src/renderer/extensions/firstRunTour/tour/canvasCoachTarget.test.ts index e407852baf5..50910f12688 100644 --- a/src/renderer/extensions/firstRunTour/tour/canvasCoachTarget.test.ts +++ b/src/renderer/extensions/firstRunTour/tour/canvasCoachTarget.test.ts @@ -92,8 +92,6 @@ describe('canvasNodeTarget', () => { state.canvasOffset = { left: 0, top: 0 } Object.assign(state.camera, { x: 0, y: 0, z: 1 }) if (state.layout) state.layout.value = null - state.layoutReads.mockClear() - state.releaseBounds.mockClear() }) it('releases what it watches when the tour drops it', () => { diff --git a/src/renderer/extensions/vueNodes/widgets/components/WidgetRecordAudio.test.ts b/src/renderer/extensions/vueNodes/widgets/components/WidgetRecordAudio.test.ts index 105169af211..29de7eef68f 100644 --- a/src/renderer/extensions/vueNodes/widgets/components/WidgetRecordAudio.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/components/WidgetRecordAudio.test.ts @@ -1,7 +1,7 @@ import { getActivePinia } from 'pinia' import { render, screen } from '@testing-library/vue' import userEvent from '@testing-library/user-event' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { defineComponent, ref } from 'vue' import { createI18n } from 'vue-i18n' @@ -282,11 +282,6 @@ describe('WidgetRecordAudio', () => { vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) }) - afterEach(() => { - vi.mocked(URL.createObjectURL).mockRestore() - vi.mocked(URL.revokeObjectURL).mockRestore() - }) - it('replaces the audio widget element src with a new blob URL when a recording completes', async () => { const audioWidget = createAudioWidget() primeAudioWidgetInNode([audioWidget]) diff --git a/src/services/customerEventsService.test.ts b/src/services/customerEventsService.test.ts index f466f4894e7..67599e38666 100644 --- a/src/services/customerEventsService.test.ts +++ b/src/services/customerEventsService.test.ts @@ -82,7 +82,6 @@ describe('useCustomerEventsService', () => { } beforeEach(() => { - vi.mocked(webSessionResourceHeader).mockReset() vi.mocked(webSessionResourceHeader).mockResolvedValue(undefined) vi.mocked(useAuthStore().getUserAuthHeader).mockResolvedValue( mockAuthHeaders diff --git a/src/services/gateway/registrySearchGateway.test.ts b/src/services/gateway/registrySearchGateway.test.ts index 94e55b1ad65..39d314cb142 100644 --- a/src/services/gateway/registrySearchGateway.test.ts +++ b/src/services/gateway/registrySearchGateway.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { useRegistrySearchGateway } from '@/services/gateway/registrySearchGateway' import { useAlgoliaSearchProvider } from '@/services/providers/algoliaSearchProvider' @@ -9,17 +9,9 @@ vi.mock(import('@/services/providers/algoliaSearchProvider')) vi.mock(import('@/services/providers/registrySearchProvider')) describe('useRegistrySearchGateway', () => { - let consoleWarnSpy: ReturnType - let consoleInfoSpy: ReturnType - beforeEach(() => { - consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation(() => {}) - }) - - afterEach(() => { - consoleWarnSpy.mockRestore() - consoleInfoSpy.mockRestore() + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'info').mockImplementation(() => {}) }) describe('Provider initialization', () => { diff --git a/src/stores/assetsStore.test.ts b/src/stores/assetsStore.test.ts index b7059dcb92f..b3263f47d95 100644 --- a/src/stores/assetsStore.test.ts +++ b/src/stores/assetsStore.test.ts @@ -833,14 +833,8 @@ describe('assetsStore - Model Assets Cache (Cloud)', () => { }) describe('updateAssetTags partial-failure compensation', () => { - let consoleSpy: ReturnType - beforeEach(() => { - consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - }) - - afterEach(() => { - consoleSpy.mockRestore() + vi.spyOn(console, 'error').mockImplementation(() => {}) }) it('re-adds removed tags when add fails so cache and server converge', async () => { diff --git a/src/stores/workspace/sidebarTabStore.test.ts b/src/stores/workspace/sidebarTabStore.test.ts index e6522deef1d..51b391b3918 100644 --- a/src/stores/workspace/sidebarTabStore.test.ts +++ b/src/stores/workspace/sidebarTabStore.test.ts @@ -85,7 +85,6 @@ vi.mock( describe('useSidebarTabStore', () => { beforeEach(() => { vi.mocked(useMenuItemStore().registerCommands).mockImplementation(() => {}) - mockOpenModelLibraryBrowser.mockClear() }) const toggleModelLibrary = async () => { diff --git a/src/workbench/extensions/agent/components/agent/message/ReplyAssetGroup.test.ts b/src/workbench/extensions/agent/components/agent/message/ReplyAssetGroup.test.ts index aba94bcb1aa..3f71adb84da 100644 --- a/src/workbench/extensions/agent/components/agent/message/ReplyAssetGroup.test.ts +++ b/src/workbench/extensions/agent/components/agent/message/ReplyAssetGroup.test.ts @@ -77,10 +77,10 @@ const toggle = () => describe('ReplyAssetGroup', () => { beforeEach(() => { - isAssetPreviewSupported.mockReset().mockReturnValue(false) - findServerPreviewUrl.mockReset().mockResolvedValue(null) - findOutputAsset.mockReset().mockResolvedValue(undefined) - generateModelThumbnail.mockReset().mockResolvedValue(null) + isAssetPreviewSupported.mockReturnValue(false) + findServerPreviewUrl.mockResolvedValue(null) + findOutputAsset.mockResolvedValue(undefined) + generateModelThumbnail.mockResolvedValue(null) }) it('T-09 / PM-652 / FE-1326 renders image and video previews inline', () => { diff --git a/src/workbench/extensions/agent/components/agent/message/ReplyAudioCard.test.ts b/src/workbench/extensions/agent/components/agent/message/ReplyAudioCard.test.ts index 4dc12f90d5c..e7ed6466d99 100644 --- a/src/workbench/extensions/agent/components/agent/message/ReplyAudioCard.test.ts +++ b/src/workbench/extensions/agent/components/agent/message/ReplyAudioCard.test.ts @@ -48,9 +48,7 @@ describe('ReplyAudioCard', () => { beforeEach(() => { vi.mocked(api.apiURL).mockImplementation((route) => `http://x/api${route}`) - vi.mocked(api.fetchApi) - .mockReset() - .mockResolvedValue(new Response(new Blob(['x']))) + vi.mocked(api.fetchApi).mockResolvedValue(new Response(new Blob(['x']))) vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock') vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) anchorClick = vi diff --git a/src/workbench/extensions/agent/crdt/docOpMinter.test.ts b/src/workbench/extensions/agent/crdt/docOpMinter.test.ts index f1efc598911..50c647b31b3 100644 --- a/src/workbench/extensions/agent/crdt/docOpMinter.test.ts +++ b/src/workbench/extensions/agent/crdt/docOpMinter.test.ts @@ -153,7 +153,6 @@ describe('attachDocOpMinter', () => { let docInputNames: DocOpMinterDeps['docInputNames'] beforeEach(() => { - vi.mocked(reportError).mockClear() graph = new LGraph() rootGraphId = toRootGraphId(graph.id) minted = [] diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index 3617bdcb5ea..c3475ee3d07 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { api } from '@/scripts/api' @@ -65,10 +65,6 @@ const turnAccepted = { workflow_id: 'w1' } -beforeEach(() => { - vi.mocked(api.fetchApi).mockReset() -}) - describe('agentRestClient route + method', () => { it('postMessage targets the literal "new" thread path to open a thread', async () => { respond(jsonResponse(202, turnAccepted)) diff --git a/tools/oxlint-plugins/vitestCleanup.test.ts b/tools/oxlint-plugins/vitestCleanup.test.ts index cd429bd3f58..ff75b8fb018 100644 --- a/tools/oxlint-plugins/vitestCleanup.test.ts +++ b/tools/oxlint-plugins/vitestCleanup.test.ts @@ -257,10 +257,44 @@ LiteGraph.unregisterNodeType() LiteGraph.clearRegisteredTypes() ` -function expectReportsAt(output: string, lines: readonly number[]) { +const mockInstanceFixture = `import { afterAll, afterEach, beforeAll, beforeEach, it, vi } from 'vitest' + +const mock = vi.fn() +const other = vi.fn() + +afterEach(() => mock.mockRestore()) +afterAll(() => { + mock.mockClear() +}) +beforeAll(() => vi.mocked(mock).mockReset()) +beforeEach(() => { + other.mockReturnValue(1) + mock.mockReset().mockReturnValue(2) + mock.mockClear() + render() + other.mockClear() +}) +beforeEach(() => mock?.mockClear()) +it('allows per-mock cleanup in tests', () => { + mock.mockClear() + mock.mockReset() + mock.mockRestore() +}) +afterEach(() => { + const helper = () => mock.mockClear() + helper() +}) +function render() {} +` + +function expectReportsAt( + output: string, + lines: readonly number[], + file = 'invalid.test.ts' +) { const plainOutput = stripVTControlCharacters(output) for (const line of lines) { - expect(plainOutput).toContain(`invalid.test.ts:${line}:`) + expect(plainOutput).toContain(`${file}:${line}:`) } } @@ -272,6 +306,10 @@ describe('Vitest cleanup rules', () => { workDir = mkdtempSync(path.join(tmpdir(), 'comfy-vitest-cleanup-')) writeFileSync(path.join(workDir, 'invalid.test.ts'), invalidFixture) writeFileSync(path.join(workDir, 'litegraph.test.ts'), liteGraphFixture) + writeFileSync( + path.join(workDir, 'mock-instance.test.ts'), + mockInstanceFixture + ) writeFileSync(path.join(workDir, 'unrelated.test.ts'), unrelatedFixture) writeFileSync(path.join(workDir, 'playwright.spec.ts'), invalidFixture) writeFileSync( @@ -300,6 +338,7 @@ describe('Vitest cleanup rules', () => { path.join(workDir, '.oxlintrc.json'), 'invalid.test.ts', 'litegraph.test.ts', + 'mock-instance.test.ts', 'unrelated.test.ts', 'playwright.spec.ts' ], @@ -354,6 +393,11 @@ describe('Vitest cleanup rules', () => { expectReportsAt(output, [73, 74, 75, 76, 77, 80, 131, 136, 137, 138]) }) + it('reports per-mock cleanup in hooks unless beforeEach setup ran first', () => { + expect(output.match(/resets and restores every mock/g)).toHaveLength(6) + expectReportsAt(output, [6, 8, 10, 13, 14, 18], 'mock-instance.test.ts') + }) + it('reports persistent LiteGraph registrations and redundant cleanup', () => { expect( output.match(/Register LiteGraph node types in beforeEach or a test/g) diff --git a/tools/oxlint-plugins/vitestCleanup.ts b/tools/oxlint-plugins/vitestCleanup.ts index 6b1072105d2..bf73f77f86f 100644 --- a/tools/oxlint-plugins/vitestCleanup.ts +++ b/tools/oxlint-plugins/vitestCleanup.ts @@ -5,6 +5,11 @@ const REDUNDANT_CLEANUP_METHODS = new Set([ 'unstubAllEnvs', 'unstubAllGlobals' ]) +const REDUNDANT_MOCK_INSTANCE_CLEANUP_METHODS = new Set([ + 'mockClear', + 'mockReset', + 'mockRestore' +]) const REDUNDANT_TIMER_CLEANUP_METHODS = new Set([ 'clearAllTimers', 'useRealTimers' @@ -17,6 +22,8 @@ const REDUNDANT_LITEGRAPH_CLEANUP_METHODS = new Set([ const MODULE_SCOPE_MOCK_METHODS = new Set(['spyOn', 'stubGlobal']) const PARTIAL_MOCK_METHODS = new Set(['doMock', 'mock']) const AFTER_EACH_IMPORTS = new Set(['afterEach']) +const BEFORE_EACH_IMPORTS = new Set(['beforeEach']) +const NON_BEFORE_EACH_HOOKS = new Set(['afterAll', 'afterEach', 'beforeAll']) const BEFORE_TEST_IMPORTS = new Set(['beforeAll', 'describe', 'suite']) const SUITE_CALLBACK_MODIFIERS = new Set([ 'concurrent', @@ -102,6 +109,16 @@ interface FunctionExpression extends Node { readonly params: readonly Node[] } +interface ExpressionStatement extends Node { + readonly type: 'ExpressionStatement' + readonly expression: Expression +} + +interface BlockStatement extends Node { + readonly type: 'BlockStatement' + readonly body: readonly Node[] +} + function isImportExpression(node: Node | undefined): node is ImportExpression { return node?.type === 'ImportExpression' } @@ -426,10 +443,63 @@ function runsBeforeTests(context: RuleContext, node: CallExpression): boolean { ) } +function calledMemberName(node: Node | undefined): string | undefined { + if (node?.type !== 'CallExpression') return + const member = asMemberExpression((node as CallExpression).callee) + return member && staticMemberName(member) +} + +function isMockConfiguration(statement: Node): boolean { + if (statement.type !== 'ExpressionStatement') return false + const methodName = calledMemberName( + unwrapChain((statement as ExpressionStatement).expression) + ) + return methodName?.startsWith('mock') === true +} + +function precedesBeforeEachSetup( + context: RuleContext, + node: CallExpression +): boolean { + const ancestors = context.sourceCode.getAncestors(node) + const boundaryIndex = enclosingExecutionBoundaryIndex(ancestors) + const body = ancestors[boundaryIndex + 1] + if (body.type !== 'BlockStatement') return true + const statements = (body as BlockStatement).body + const statementIndex = statements.findIndex( + (statement) => statement === ancestors[boundaryIndex + 2] + ) + return statements.slice(0, statementIndex).every(isMockConfiguration) +} + +function isRedundantMockInstanceCleanup( + context: RuleContext, + node: CallExpression +): boolean { + return ( + runsDirectlyInVitestCallback(context, node, NON_BEFORE_EACH_HOOKS) || + (runsDirectlyInVitestCallback(context, node, BEFORE_EACH_IMPORTS) && + precedesBeforeEachSetup(context, node)) + ) +} + export const noRedundantVitestCleanup = { create(context: RuleContext) { return { CallExpression(node: CallExpression) { + const mockMethodName = calledMemberName(node) + if ( + mockMethodName && + REDUNDANT_MOCK_INSTANCE_CLEANUP_METHODS.has(mockMethodName) && + isRedundantMockInstanceCleanup(context, node) + ) { + context.report({ + node, + message: `.${mockMethodName}() is redundant in a Vitest hook because the project test setup resets and restores every mock before each test.` + }) + return + } + const methodName = vitestMethodName(context, node) if ( !methodName || diff --git a/tools/test-recorder/src/pr/gh.test.ts b/tools/test-recorder/src/pr/gh.test.ts index 000552d9b4f..9793e176f3b 100644 --- a/tools/test-recorder/src/pr/gh.test.ts +++ b/tools/test-recorder/src/pr/gh.test.ts @@ -30,7 +30,6 @@ describe('createPr', () => { let consoleLines: string[] beforeEach(() => { - runMock.mockReset() consoleLines = [] vi.spyOn(console, 'log').mockImplementation((value?: unknown) => { consoleLines.push(String(value ?? '')) From b216fe0bcb658c297ec5d607349b1401aa0d69f7 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Sat, 3 Oct 2026 07:31:48 +0000 Subject: [PATCH 2/7] fix: guard concise beforeEach bodies and keep resets after mock configuration Amp-Thread-ID: https://ampcode.com/threads/T-01a0fedc-ff89-70cb-a069-0b7f4feb4985 --- tools/oxlint-plugins/vitestCleanup.test.ts | 16 ++++++++++++---- tools/oxlint-plugins/vitestCleanup.ts | 13 ++++++++----- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/tools/oxlint-plugins/vitestCleanup.test.ts b/tools/oxlint-plugins/vitestCleanup.test.ts index ff75b8fb018..6103b6047f7 100644 --- a/tools/oxlint-plugins/vitestCleanup.test.ts +++ b/tools/oxlint-plugins/vitestCleanup.test.ts @@ -268,13 +268,21 @@ afterAll(() => { }) beforeAll(() => vi.mocked(mock).mockReset()) beforeEach(() => { - other.mockReturnValue(1) + other.mockClear() mock.mockReset().mockReturnValue(2) - mock.mockClear() render() other.mockClear() }) beforeEach(() => mock?.mockClear()) +beforeEach(() => mock.mockClear()) +beforeEach(() => { + mock.mockReturnValue(1) + mock.mockReset() +}) +beforeEach(() => { + mock.mockReturnValue(1) + mock.mockRestore() +}) it('allows per-mock cleanup in tests', () => { mock.mockClear() mock.mockReset() @@ -394,8 +402,8 @@ describe('Vitest cleanup rules', () => { }) it('reports per-mock cleanup in hooks unless beforeEach setup ran first', () => { - expect(output.match(/resets and restores every mock/g)).toHaveLength(6) - expectReportsAt(output, [6, 8, 10, 13, 14, 18], 'mock-instance.test.ts') + expect(output.match(/resets and restores every mock/g)).toHaveLength(7) + expectReportsAt(output, [6, 8, 10, 12, 13, 17, 18], 'mock-instance.test.ts') }) it('reports persistent LiteGraph registrations and redundant cleanup', () => { diff --git a/tools/oxlint-plugins/vitestCleanup.ts b/tools/oxlint-plugins/vitestCleanup.ts index bf73f77f86f..5a1951448a0 100644 --- a/tools/oxlint-plugins/vitestCleanup.ts +++ b/tools/oxlint-plugins/vitestCleanup.ts @@ -449,12 +449,15 @@ function calledMemberName(node: Node | undefined): string | undefined { return member && staticMemberName(member) } -function isMockConfiguration(statement: Node): boolean { +function isMockInstanceCleanup(statement: Node): boolean { if (statement.type !== 'ExpressionStatement') return false const methodName = calledMemberName( unwrapChain((statement as ExpressionStatement).expression) ) - return methodName?.startsWith('mock') === true + return ( + methodName !== undefined && + REDUNDANT_MOCK_INSTANCE_CLEANUP_METHODS.has(methodName) + ) } function precedesBeforeEachSetup( @@ -463,13 +466,13 @@ function precedesBeforeEachSetup( ): boolean { const ancestors = context.sourceCode.getAncestors(node) const boundaryIndex = enclosingExecutionBoundaryIndex(ancestors) - const body = ancestors[boundaryIndex + 1] - if (body.type !== 'BlockStatement') return true + const body = ancestors.at(boundaryIndex + 1) + if (body?.type !== 'BlockStatement') return true const statements = (body as BlockStatement).body const statementIndex = statements.findIndex( (statement) => statement === ancestors[boundaryIndex + 2] ) - return statements.slice(0, statementIndex).every(isMockConfiguration) + return statements.slice(0, statementIndex).every(isMockInstanceCleanup) } function isRedundantMockInstanceCleanup( From e5530edb39b27d6f4debedb10fec35f3b1edb367 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Mon, 5 Oct 2026 03:29:01 +0000 Subject: [PATCH 3/7] fix: only report cleanup on receivers that resolve to Vitest mocks Amp-Thread-ID: https://ampcode.com/threads/T-01a0fedc-ff89-70cb-a069-0b7f4feb4985 --- tools/oxlint-plugins/vitestCleanup.test.ts | 34 ++- tools/oxlint-plugins/vitestCleanup.ts | 306 +++++++++++++++++++-- 2 files changed, 319 insertions(+), 21 deletions(-) diff --git a/tools/oxlint-plugins/vitestCleanup.test.ts b/tools/oxlint-plugins/vitestCleanup.test.ts index 6103b6047f7..db619463152 100644 --- a/tools/oxlint-plugins/vitestCleanup.test.ts +++ b/tools/oxlint-plugins/vitestCleanup.test.ts @@ -293,6 +293,30 @@ afterEach(() => { helper() }) function render() {} +import { reportError } from './reportError' +import { track } from './unmocked' +vi.mock('./reportError') +const { hoistedMock } = vi.hoisted(() => ({ hoistedMock: vi.fn() })) +const mocks = { nested: { fn: vi.fn() } } +const cache = { mockClear() {}, mockReset() {}, mockRestore() {} } +let spy +beforeEach(() => { + spy = vi.spyOn(console, 'warn') +}) +afterEach(() => { + reportError.mockClear() + hoistedMock.mockReset() + mocks.nested.fn.mockReset() + spy.mockRestore() + vi.mocked(useThing()).method.mockClear() + cache.mockClear() + cache.mockReset() + cache.mockRestore() + track.mockClear() +}) +function useThing() { + return { method() {} } +} ` function expectReportsAt( @@ -401,9 +425,13 @@ describe('Vitest cleanup rules', () => { expectReportsAt(output, [73, 74, 75, 76, 77, 80, 131, 136, 137, 138]) }) - it('reports per-mock cleanup in hooks unless beforeEach setup ran first', () => { - expect(output.match(/resets and restores every mock/g)).toHaveLength(7) - expectReportsAt(output, [6, 8, 10, 12, 13, 17, 18], 'mock-instance.test.ts') + it('reports Vitest mock cleanup in hooks unless beforeEach setup ran first', () => { + expect(output.match(/resets and restores every mock/g)).toHaveLength(12) + expectReportsAt( + output, + [6, 8, 10, 12, 13, 17, 18, 48, 49, 50, 51, 52], + 'mock-instance.test.ts' + ) }) it('reports persistent LiteGraph registrations and redundant cleanup', () => { diff --git a/tools/oxlint-plugins/vitestCleanup.ts b/tools/oxlint-plugins/vitestCleanup.ts index 5a1951448a0..31c41ecbc7b 100644 --- a/tools/oxlint-plugins/vitestCleanup.ts +++ b/tools/oxlint-plugins/vitestCleanup.ts @@ -19,6 +19,13 @@ const REDUNDANT_LITEGRAPH_CLEANUP_METHODS = new Set([ 'unregisterNodeType' ]) +const MOCK_FACTORY_METHODS = new Set(['fn', 'mocked', 'spyOn']) +const TYPE_WRAPPERS = new Set([ + 'ParenthesizedExpression', + 'TSAsExpression', + 'TSNonNullExpression', + 'TSSatisfiesExpression' +]) const MODULE_SCOPE_MOCK_METHODS = new Set(['spyOn', 'stubGlobal']) const PARTIAL_MOCK_METHODS = new Set(['doMock', 'mock']) const AFTER_EACH_IMPORTS = new Set(['afterEach']) @@ -107,6 +114,42 @@ interface FunctionExpression extends Node { | 'FunctionDeclaration' | 'FunctionExpression' readonly params: readonly Node[] + readonly body: Node +} + +interface Property extends Node { + readonly type: 'Property' + readonly key: Expression + readonly value: Expression + readonly computed: boolean +} + +interface ObjectExpression extends Node { + readonly type: 'ObjectExpression' + readonly properties: readonly Node[] +} + +interface ObjectPattern extends Node { + readonly type: 'ObjectPattern' + readonly properties: readonly Node[] +} + +interface ReturnStatement extends Node { + readonly type: 'ReturnStatement' + readonly argument: Expression | null +} + +interface AwaitExpression extends Node { + readonly type: 'AwaitExpression' + readonly argument: Expression +} + +interface WrappedExpression extends Node { + readonly expression: Expression +} + +interface Program extends Node { + readonly body: readonly Node[] } interface ExpressionStatement extends Node { @@ -151,6 +194,7 @@ function isFunctionExpression( interface ScopeVariableDefinition { readonly type: string readonly node: Node & { + readonly id?: Node readonly imported?: Identifier readonly init?: Expression } @@ -159,6 +203,7 @@ interface ScopeVariableDefinition { interface ScopeVariable { readonly defs: readonly ScopeVariableDefinition[] + readonly references: readonly { readonly writeExpr: Expression | null }[] } interface ScopeReference { @@ -475,6 +520,237 @@ function precedesBeforeEachSetup( return statements.slice(0, statementIndex).every(isMockInstanceCleanup) } +function unwrapExpression(expression: Expression): Expression { + let current = unwrapChain(expression) + while ( + TYPE_WRAPPERS.has(current.type) || + current.type === 'AwaitExpression' + ) { + current = unwrapChain( + current.type === 'AwaitExpression' + ? (current as AwaitExpression).argument + : (current as WrappedExpression).expression + ) + } + return current +} + +function staticPropertyName(property: Property): string | undefined { + if (!property.computed && property.key.type === 'Identifier') { + return (property.key as Identifier).name + } + const value = (property.key as StringLiteral).value + if (typeof value === 'string') return value +} + +function propertyValue( + object: Expression, + name: string +): Expression | undefined { + if (object.type !== 'ObjectExpression') return + return (object as ObjectExpression).properties.find( + (property): property is Property => + property.type === 'Property' && + staticPropertyName(property as Property) === name + )?.value +} + +function hoistedValue( + context: RuleContext, + call: CallExpression +): Expression | undefined { + const factory = call.arguments[0] + if ( + vitestMethodName(context, call) !== 'hoisted' || + !isFunctionExpression(factory) + ) { + return + } + if (factory.body.type !== 'BlockStatement') return factory.body + const returned = (factory.body as BlockStatement).body.find( + (statement) => statement.type === 'ReturnStatement' + ) as ReturnStatement | undefined + return returned?.argument ?? undefined +} + +const MAX_RESOLUTION_DEPTH = 8 + +function destructuredValues( + context: RuleContext, + definition: ScopeVariableDefinition, + name: string, + depth: number +): Expression[] { + const { id, init } = definition.node + if (id?.type !== 'ObjectPattern' || !init) return [] + const key = (id as ObjectPattern).properties + .filter((property): property is Property => property.type === 'Property') + .find( + (property) => asIdentifier(unwrapChain(property.value))?.name === name + ) + const keyName = key && staticPropertyName(key) + if (!keyName) return [] + return resolveValues(context, init, depth + 1).flatMap((object) => { + const value = propertyValue(object, keyName) + return value ? resolveValues(context, value, depth + 1) : [] + }) +} + +function resolveValues( + context: RuleContext, + expression: Expression, + depth = 0 +): Expression[] { + const value = unwrapExpression(expression) + if (depth > MAX_RESOLUTION_DEPTH) return [value] + + if (value.type === 'Identifier') { + return identifierValues(context, value as Identifier, depth) + } + if (value.type === 'CallExpression') { + const hoisted = hoistedValue(context, value as CallExpression) + return hoisted ? resolveValues(context, hoisted, depth + 1) : [value] + } + const member = asMemberExpression(value) + return member ? memberValues(context, member, depth) : [value] +} + +function identifierValues( + context: RuleContext, + identifier: Identifier, + depth: number +): Expression[] { + const variable = resolvedVariable(context, identifier) + if (!variable) return [identifier] + return [ + identifier, + ...variable.defs.flatMap((definition) => + destructuredValues(context, definition, identifier.name, depth) + ), + ...variable.references.flatMap(({ writeExpr }) => + writeExpr ? resolveValues(context, writeExpr, depth + 1) : [] + ) + ] +} + +function memberValues( + context: RuleContext, + member: MemberExpression, + depth: number +): Expression[] { + const name = staticMemberName(member) + if (!name) return [member] + const resolved = resolveValues(context, member.object, depth + 1).flatMap( + (object) => { + const property = propertyValue(object, name) + return property ? resolveValues(context, property, depth + 1) : [] + } + ) + return resolved.length > 0 ? resolved : [member] +} + +function isMockedModuleImport( + context: RuleContext, + identifier: Identifier, + mockedModules: ReadonlySet +): boolean { + return ( + resolvedVariable(context, identifier)?.defs.some( + (definition) => + definition.type === 'ImportBinding' && + typeof definition.parent.source?.value === 'string' && + mockedModules.has(definition.parent.source.value) + ) === true + ) +} + +function isVitestMock( + context: RuleContext, + expression: Expression, + mockedModules: ReadonlySet, + depth = 0 +): boolean { + if (depth > MAX_RESOLUTION_DEPTH) return false + return resolveValues(context, expression).some((value) => { + if (value.type === 'Identifier') { + return isMockedModuleImport(context, value as Identifier, mockedModules) + } + if (value.type === 'CallExpression') { + const call = value as CallExpression + const factory = vitestMethodName(context, call) + if (factory && MOCK_FACTORY_METHODS.has(factory)) return true + const member = asMemberExpression(call.callee) + return ( + member !== undefined && + staticMemberName(member)?.startsWith('mock') === true && + isVitestMock(context, member.object, mockedModules, depth + 1) + ) + } + const member = asMemberExpression(value) + return ( + member !== undefined && + resolveValues(context, member.object).some( + (object) => + object.type === 'CallExpression' && + vitestMethodName(context, object as CallExpression) === 'mocked' + ) + ) + }) +} + +function vitestMockedModules( + context: RuleContext, + program: Program +): Set { + return new Set( + program.body.flatMap((statement) => { + if (statement.type !== 'ExpressionStatement') return [] + const call = unwrapChain((statement as ExpressionStatement).expression) + if ( + call.type !== 'CallExpression' || + vitestMethodName(context, call as CallExpression) !== 'mock' + ) { + return [] + } + const moduleName = staticModuleName((call as CallExpression).arguments[0]) + return moduleName ? [moduleName] : [] + }) + ) +} + +function redundantMockInstanceCleanupName( + context: RuleContext, + node: CallExpression, + mockedModules: ReadonlySet +): string | undefined { + const member = asMemberExpression(node.callee) + const methodName = member && staticMemberName(member) + if ( + methodName && + REDUNDANT_MOCK_INSTANCE_CLEANUP_METHODS.has(methodName) && + isRedundantMockInstanceCleanup(context, node) && + isVitestMock(context, member.object, mockedModules) + ) { + return methodName + } +} + +function redundantVitestCleanupName( + context: RuleContext, + node: CallExpression +): string | undefined { + const methodName = vitestMethodName(context, node) + if (!methodName) return + if ( + (REDUNDANT_CLEANUP_METHODS.has(methodName) && + runsDirectlyInVitestCallback(context, node)) || + (REDUNDANT_TIMER_CLEANUP_METHODS.has(methodName) && + runsDirectlyInVitestCallback(context, node, AFTER_EACH_IMPORTS)) + ) { + return methodName + } +} + function isRedundantMockInstanceCleanup( context: RuleContext, node: CallExpression @@ -488,14 +764,18 @@ function isRedundantMockInstanceCleanup( export const noRedundantVitestCleanup = { create(context: RuleContext) { + let mockedModules = new Set() return { + Program(program: Program) { + mockedModules = vitestMockedModules(context, program) + }, CallExpression(node: CallExpression) { - const mockMethodName = calledMemberName(node) - if ( - mockMethodName && - REDUNDANT_MOCK_INSTANCE_CLEANUP_METHODS.has(mockMethodName) && - isRedundantMockInstanceCleanup(context, node) - ) { + const mockMethodName = redundantMockInstanceCleanupName( + context, + node, + mockedModules + ) + if (mockMethodName) { context.report({ node, message: `.${mockMethodName}() is redundant in a Vitest hook because the project test setup resets and restores every mock before each test.` @@ -503,18 +783,8 @@ export const noRedundantVitestCleanup = { return } - const methodName = vitestMethodName(context, node) - if ( - !methodName || - !( - (REDUNDANT_CLEANUP_METHODS.has(methodName) && - runsDirectlyInVitestCallback(context, node)) || - (REDUNDANT_TIMER_CLEANUP_METHODS.has(methodName) && - runsDirectlyInVitestCallback(context, node, AFTER_EACH_IMPORTS)) - ) - ) { - return - } + const methodName = redundantVitestCleanupName(context, node) + if (!methodName) return context.report({ node, message: `vi.${methodName}() is redundant in a Vitest hook because the project test setup performs this cleanup automatically.` From 9f0feb11ccaa8c0434a6745ff94ae8783c418144 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Mon, 5 Oct 2026 03:54:53 +0000 Subject: [PATCH 4/7] fix: ban members named after Vitest mock cleanup methods instead of resolving receivers Amp-Thread-ID: https://ampcode.com/threads/T-01a0fedc-ff89-70cb-a069-0b7f4feb4985 --- .oxlintrc.json | 7 + apps/website/src/scripts/posthog.test.ts | 20 +- .../cloud/PostHogTelemetryProvider.test.ts | 10 +- tools/oxlint-plugins/comfy.ts | 8 +- tools/oxlint-plugins/restrictedSyntax.test.ts | 46 +++ tools/oxlint-plugins/restrictedSyntax.ts | 56 ++++ tools/oxlint-plugins/vitestCleanup.test.ts | 34 +- tools/oxlint-plugins/vitestCleanup.ts | 306 ++---------------- 8 files changed, 153 insertions(+), 334 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index c392e87e617..26aef581d3d 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -41,6 +41,7 @@ "comfy/no-duplicate-ingest-type": "error", "comfy/no-relative-packages": "error", "comfy/no-js-private-class-members": "error", + "comfy/no-vitest-mock-method-names": "error", "comfy/no-render-in-watch-effect": "error", "comfy/no-useless-path-segments": "error", "no-array-constructor": "error", @@ -290,6 +291,12 @@ ] } }, + { + "files": ["**/vite.config.*", "**/vitest.config.*", "vitest.*.mts"], + "rules": { + "comfy/no-vitest-mock-method-names": "off" + } + }, { "files": ["src/**/*.{js,mjs,cjs,ts,mts,cts,vue}"], "excludeFiles": ["src/**/*.test.{ts,tsx}"], diff --git a/apps/website/src/scripts/posthog.test.ts b/apps/website/src/scripts/posthog.test.ts index 79eb32dda57..c2daf5568ca 100644 --- a/apps/website/src/scripts/posthog.test.ts +++ b/apps/website/src/scripts/posthog.test.ts @@ -17,7 +17,7 @@ const hoisted = vi.hoisted(() => ({ mockIsFeatureEnabled: vi.fn(), mockGetFeatureFlag: vi.fn(), mockIdentify: vi.fn(), - mockReset: vi.fn(), + mockPosthogReset: vi.fn(), mockGetProperty: vi.fn(), mockReloadFeatureFlags: vi.fn(), mockSetPersonPropertiesForFlags: vi.fn() @@ -62,7 +62,7 @@ const postHogMock = { isFeatureEnabled: hoisted.mockIsFeatureEnabled, getFeatureFlag: hoisted.mockGetFeatureFlag, identify: hoisted.mockIdentify, - reset: hoisted.mockReset, + reset: hoisted.mockPosthogReset, get_property: hoisted.mockGetProperty, reloadFeatureFlags: hoisted.mockReloadFeatureFlags, setPersonPropertiesForFlags: hoisted.mockSetPersonPropertiesForFlags @@ -200,14 +200,16 @@ describe('Workshop visibility', () => { hoisted.mockSetPersonPropertiesForFlags.mockClear() hoisted.mockGetProperty.mockReturnValue('signed-in-before') identifyWorkshopUser({ uid: 'someone-else' }) - expect(hoisted.mockReset).toHaveBeenCalled() + expect(hoisted.mockPosthogReset).toHaveBeenCalled() expect(hoisted.mockSetPersonPropertiesForFlags).toHaveBeenCalledWith( environment, false ) expect( hoisted.mockSetPersonPropertiesForFlags.mock.invocationCallOrder[0] - ).toBeGreaterThan(hoisted.mockReset.mock.invocationCallOrder.at(-1) ?? 0) + ).toBeGreaterThan( + hoisted.mockPosthogReset.mock.invocationCallOrder.at(-1) ?? 0 + ) }) it('requires an explicit enable and keeps the last answer through load failures', async () => { @@ -288,7 +290,7 @@ describe('Workshop visibility', () => { emitFeatureFlags() identifyWorkshopUser(null) expect(useWorkshopEnabled().value).toBe(false) - expect(hoisted.mockReset).toHaveBeenCalledTimes(2) + expect(hoisted.mockPosthogReset).toHaveBeenCalledTimes(2) expect(hoisted.mockReloadFeatureFlags).toHaveBeenCalledTimes(3) }) @@ -436,7 +438,9 @@ describe('Workshop visibility', () => { emitFeatureFlags() vi.spyOn(console, 'error').mockImplementation(() => undefined) const call = - operation === 'identify' ? hoisted.mockIdentify : hoisted.mockReset + operation === 'identify' + ? hoisted.mockIdentify + : hoisted.mockPosthogReset call.mockImplementationOnce(() => { throw new Error('Unavailable') }) @@ -455,14 +459,14 @@ describe('Workshop visibility', () => { const { initPostHog, identifyWorkshopUser } = await import('./posthog') initPostHog() identifyWorkshopUser(null) - expect(hoisted.mockReset).not.toHaveBeenCalled() + expect(hoisted.mockPosthogReset).not.toHaveBeenCalled() vi.resetModules() hoisted.mockGetProperty.mockReturnValue('previous-user') const restored = await import('./posthog') restored.initPostHog() restored.identifyWorkshopUser(null) - expect(hoisted.mockReset).toHaveBeenCalledOnce() + expect(hoisted.mockPosthogReset).toHaveBeenCalledOnce() }) }) diff --git a/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.test.ts b/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.test.ts index 1bccbf9a8b1..5e85c708965 100644 --- a/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.test.ts +++ b/src/platform/telemetry/providers/cloud/PostHogTelemetryProvider.test.ts @@ -26,7 +26,7 @@ const hoisted = vi.hoisted(() => { const mockPeopleSet = vi.fn() const mockPeopleSetOnce = vi.fn() const mockRegister = vi.fn() - const mockReset = vi.fn() + const mockPosthogReset = vi.fn() const executionContext = { is_template: true, workflow_name: 'image_qwen_image_edit_2509', @@ -54,7 +54,7 @@ const hoisted = vi.hoisted(() => { mockPeopleSet, mockPeopleSetOnce, mockRegister, - mockReset, + mockPosthogReset, executionContext, agentPanelOpen: false, refs, @@ -65,7 +65,7 @@ const hoisted = vi.hoisted(() => { identify: mockIdentify, register: mockRegister, people: { set: mockPeopleSet, set_once: mockPeopleSetOnce }, - reset: mockReset + reset: mockPosthogReset } } } @@ -1669,14 +1669,14 @@ describe('PostHogTelemetryProvider', () => { const callback = vi.mocked(useCurrentUser().onUserLogout).mock.calls[0][0] callback() - expect(hoisted.mockReset).toHaveBeenCalledWith(true) + expect(hoisted.mockPosthogReset).toHaveBeenCalledWith(true) }) it('does not register the watcher before init resolves', () => { createProvider() expect(useCurrentUser().onUserLogout).not.toHaveBeenCalled() - expect(hoisted.mockReset).not.toHaveBeenCalled() + expect(hoisted.mockPosthogReset).not.toHaveBeenCalled() }) }) diff --git a/tools/oxlint-plugins/comfy.ts b/tools/oxlint-plugins/comfy.ts index 699d96abcfd..8dd3d2481a2 100644 --- a/tools/oxlint-plugins/comfy.ts +++ b/tools/oxlint-plugins/comfy.ts @@ -25,7 +25,8 @@ import type { noPrimeVueImports as NoPrimeVueImports, noStaticallyDisabledTest as NoStaticallyDisabledTest, noUnitTestFilesInBrowserTests as NoUnitTestFilesInBrowserTests, - noUnsafeErrorAssertion as NoUnsafeErrorAssertion + noUnsafeErrorAssertion as NoUnsafeErrorAssertion, + noVitestMockMethodNames as NoVitestMockMethodNames } from './restrictedSyntax' import type { noImportActual as NoImportActual, @@ -71,7 +72,8 @@ const { noPrimeVueImports, noStaticallyDisabledTest, noUnitTestFilesInBrowserTests, - noUnsafeErrorAssertion + noUnsafeErrorAssertion, + noVitestMockMethodNames } = requireFrom('./restrictedSyntax.ts') as { noDeprecatedApiSchema: typeof NoDeprecatedApiSchema noDirectSelectionWrite: typeof NoDirectSelectionWrite @@ -86,6 +88,7 @@ const { noStaticallyDisabledTest: typeof NoStaticallyDisabledTest noUnitTestFilesInBrowserTests: typeof NoUnitTestFilesInBrowserTests noUnsafeErrorAssertion: typeof NoUnsafeErrorAssertion + noVitestMockMethodNames: typeof NoVitestMockMethodNames } const { noImportActual, @@ -132,6 +135,7 @@ export default { 'no-unit-test-files-in-browser-tests': noUnitTestFilesInBrowserTests, 'no-unsafe-error-assertion': noUnsafeErrorAssertion, 'no-useless-path-segments': noUselessPathSegments, + 'no-vitest-mock-method-names': noVitestMockMethodNames, 'prefer-initial-settings': preferInitialSettings, 'use-global-pinia': useGlobalPinia } diff --git a/tools/oxlint-plugins/restrictedSyntax.test.ts b/tools/oxlint-plugins/restrictedSyntax.test.ts index 685c27ac818..24c829b4d5d 100644 --- a/tools/oxlint-plugins/restrictedSyntax.test.ts +++ b/tools/oxlint-plugins/restrictedSyntax.test.ts @@ -96,6 +96,30 @@ void unrelated void Example ` }, + { + file: path.join(probeDirs.source, 'mockMethodNames.ts'), + source: `interface Cache { + mockClear(): void + mockReset: () => void +} +type Store = { mockRestore(): void } +class Fake { + mockClear() {} + mockReset = () => {} +} +const fake = { mockRestore() {}, 'mockClear': () => {}, mockReset } +const { mockReset: renamed } = source +const allowed = { reset() {}, mockFn: vi.fn() } +void (fake as Cache & Store) +void Fake +void renamed +void allowed +` + }, + { + file: path.join(probeDirs.source, 'vitest.config.ts'), + source: 'export default { test: { mockReset: true, restoreMocks: true } }\n' + }, { file: path.join(probeDirs.source, 'computed.vue'), source: `