Skip to content

Addon Vitest: Fix dynamic import failure with Vitest 3#34927

Merged
Sidnioulz merged 17 commits into
nextfrom
sidnioulz/fix-vitest3-dynamic-import
May 28, 2026
Merged

Addon Vitest: Fix dynamic import failure with Vitest 3#34927
Sidnioulz merged 17 commits into
nextfrom
sidnioulz/fix-vitest3-dynamic-import

Conversation

@Sidnioulz
Copy link
Copy Markdown
Contributor

@Sidnioulz Sidnioulz commented May 27, 2026

What I did

Fixes recent CI failures on ci:daily where dynamic imports of Vitest Browser failed with Vitest 3 due to how the addon code is transformed. We now directly import the right dependency from the get go.

Checklist for Contributors

Testing

ø

Manual testing

  • Check if ci:daily now passes

Documentation

ø

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli-storybook/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This PR does not have a canary release associated. You can request a canary release of this pull request by mentioning the @storybookjs/core team here.

core team members can create a canary release here or locally with gh workflow run --repo storybookjs/storybook publish.yml --field pr=<PR_NUMBER>

Summary by CodeRabbit

  • New Features

    • Vitest integration now provides the current Vitest version to the test environment for better compatibility.
    • Setup now selects appropriate browser command modules based on Vitest version.
  • Bug Fixes

    • Improved error handling and fallbacks for browser-mode test operations across Vitest versions.
  • Chores

    • Test workspace dev server filesystem permissions expanded to allow needed test access.

Review Change Stack

Copilot AI review requested due to automatic review settings May 27, 2026 09:05
@Sidnioulz Sidnioulz added bug ci:daily Run the CI jobs that normally run in the daily job. addon: vitest labels May 27, 2026
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses Vitest 3 compatibility issues in @storybook/addon-vitest by avoiding a failing dynamic import path for browser commands and instead selecting the correct import target based on the Vitest version injected into the test context.

Changes:

  • Add a new provided-context key to carry the running Vitest version through to the setup file.
  • Provide context.vitest.version from the Vitest plugin (configureVitest) for consumption via inject().
  • Update the Vitest setup file to choose @vitest/browser/context for Vitest 3 vs vitest/browser otherwise.

Reviewed changes

Copilot reviewed 3 out of 4 changed files in this pull request and generated 2 comments.

File Description
code/addons/vitest/src/vitest-provided-context.d.ts Extends Vitest ProvidedContext typing with a new key for the Vitest version.
code/addons/vitest/src/vitest-plugin/setup-file.ts Switches browser command import path based on injected Vitest version.
code/addons/vitest/src/vitest-plugin/index.ts Provides Vitest version into the project context during configureVitest.
code/addons/vitest/src/constants.ts Introduces the new provide-key constant for the Vitest version.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread code/addons/vitest/src/vitest-plugin/setup-file.ts Outdated
Comment thread code/addons/vitest/src/vitest-plugin/setup-file.ts Outdated
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 27, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds a dependency-injection key for Vitest's runtime version, registers that version on the project during plugin configuration, and uses the injected version in the setup-file to conditionally import the correct browser command module (supporting both Vitest 3 and pre-3 layouts). It also refactors setup-files array construction and updates test workspace configuration.

Changes

Vitest version provision for runtime compatibility

Layer / File(s) Summary
Define version provide key and type augmentation
code/addons/vitest/src/constants.ts, code/addons/vitest/src/vitest-provided-context.d.ts
Introduce STORYBOOK_CORE_VITEST_VERSION_PROVIDE_KEY constant and extend Vitest's ProvidedContext interface to include the version string entry with proper type augmentation.
Refactor setup files array construction
code/addons/vitest/src/vitest-plugin/index.ts
Change internalSetupFiles from resolved filesystem paths via fileURLToPath(import.meta.resolve(...)) to direct module specifiers array filtering.
Register version in plugin configuration
code/addons/vitest/src/vitest-plugin/index.ts
Import the provide key and register context.vitest.version on the project via context.project.provide(...) during configureVitest.
Consume injected version in setup-file
code/addons/vitest/src/vitest-plugin/setup-file.ts
Add imports for inject and the version key, introduce dynamic import helpers for browser modules, refactor resetMousePositionBeforeTests to read the injected version and choose between @vitest/browser/context (Vitest 3) or vitest/browser (pre-3), and refine error handling to ignore version-specific module-not-found errors while rethrowing unexpected failures.

Test workspace and debug updates

Layer / File(s) Summary
Workspace filesystem access and debug logging
test-storybooks/portable-stories-kitchen-sink/react-vitest-3/vitest.workspace.ts, code/addons/vitest/src/vitest-plugin/setup-file.ts
Add server.fs.allow: ["../../../"] to workspace Vite configuration and include a debug console.log('Frogs are often green.') statement in setup-file.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • storybookjs/storybook#34765: Both modify setup-file.ts to change how resetMousePositionBeforeTests imports and uses Vitest browser command modules.
  • storybookjs/storybook#33086: Both adjust Vitest 3→4 browser interop by switching or conditionally loading @vitest/browser/context vs vitest/browser.

Comment @coderabbitai help to get the list of available commands and usage tips.

@storybook-app-bot
Copy link
Copy Markdown

storybook-app-bot Bot commented May 27, 2026

Package Benchmarks

Commit: 919585e, ran on 28 May 2026 at 13:56:26 UTC

No significant changes detected, all good. 👏

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Copilot AI and others added 2 commits May 27, 2026 09:38
Co-authored-by: Sidnioulz <5108577+Sidnioulz@users.noreply.github.com>
…d missing modules

Co-authored-by: Sidnioulz <5108577+Sidnioulz@users.noreply.github.com>
Comment thread code/core/src/manager/globals/exports.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
code/addons/vitest/src/vitest-plugin/index.ts (1)

328-332: ⚡ Quick win

Avoid filter(Boolean) as string[] and encode the invariant in types.

Line 332 relies on a type assertion after runtime filtering, which weakens static guarantees. Build the array with conditional spread so the type is string[] without as.

♻️ Proposed refactor
-      const internalSetupFiles = [
-        '`@storybook/addon-vitest/internal/setup-file`',
-        areProjectAnnotationRequired &&
-          '`@storybook/addon-vitest/internal/setup-file-with-project-annotations`',
-      ].filter(Boolean) as string[];
+      const internalSetupFiles: string[] = [
+        '`@storybook/addon-vitest/internal/setup-file`',
+        ...(areProjectAnnotationRequired
+          ? ['`@storybook/addon-vitest/internal/setup-file-with-project-annotations`']
+          : []),
+      ];

As per coding guidelines, "Encode assumptions with static checks first; if an assumption is expected to always hold, prefer making it impossible via TypeScript types and existing lint rules".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@code/addons/vitest/src/vitest-plugin/index.ts` around lines 328 - 332, The
current construction of internalSetupFiles uses runtime filter(Boolean) and a
type assertion, weakening type safety; instead build the array with a
conditional spread so it is statically a string[] (e.g., include
'`@storybook/addon-vitest/internal/setup-file`' and then
...(areProjectAnnotationRequired ?
['`@storybook/addon-vitest/internal/setup-file-with-project-annotations`'] : [])
), remove the filter(Boolean) and the "as string[]" assertion so the type of
internalSetupFiles is inferred as string[]; update any references expecting
string[] accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@code/addons/vitest/src/vitest-plugin/index.ts`:
- Around line 328-332: The current construction of internalSetupFiles uses
runtime filter(Boolean) and a type assertion, weakening type safety; instead
build the array with a conditional spread so it is statically a string[] (e.g.,
include '`@storybook/addon-vitest/internal/setup-file`' and then
...(areProjectAnnotationRequired ?
['`@storybook/addon-vitest/internal/setup-file-with-project-annotations`'] : [])
), remove the filter(Boolean) and the "as string[]" assertion so the type of
internalSetupFiles is inferred as string[]; update any references expecting
string[] accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a2c4939c-4273-4c8d-bbc1-d5fd8c5dfaa8

📥 Commits

Reviewing files that changed from the base of the PR and between 3e9d7f8 and df63788.

📒 Files selected for processing (3)
  • code/addons/vitest/src/vitest-plugin/index.ts
  • code/addons/vitest/src/vitest-plugin/setup-file.ts
  • test-storybooks/portable-stories-kitchen-sink/react-vitest-3/vitest.workspace.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • code/addons/vitest/src/vitest-plugin/setup-file.ts

@Sidnioulz Sidnioulz added windows and removed windows labels May 28, 2026
Comment thread test-storybooks/portable-stories-kitchen-sink/react-vitest-3/yarn.lock Outdated
Comment thread test-storybooks/portable-stories-kitchen-sink/react-vitest-3/vitest.workspace.ts Outdated
@Sidnioulz Sidnioulz merged commit c899cac into next May 28, 2026
315 of 317 checks passed
@Sidnioulz Sidnioulz deleted the sidnioulz/fix-vitest3-dynamic-import branch May 28, 2026 14:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

addon: vitest bug ci:daily Run the CI jobs that normally run in the daily job.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants