storybookjs / storybook

Storybook is the industry standard workshop for building, documenting, and testing UI components in isolation
https://storybook.js.org
MIT License
83.4k stars 9.12k forks source link

[Bug]: Unable to Mock Modules in Storybook #28282

Open andrejilderda opened 2 weeks ago

andrejilderda commented 2 weeks ago

Describe the bug

I’ve been attempting to mock modules in one of my projects following this guide, but I can’t get it to work. The mock is never displayed inside Storybook.

I created a minimal reproduction with just a string that is exported to demonstrate the issue.

Reproduction link

https://stackblitz.com/edit/github-iojcfk

Reproduction steps

  1. Visit this Stackblitz
  2. Note how the Dummy-component renders: 🟨 actual module
  3. I expect it to be: ✅ mocked dependency

System

Storybook Environment Info:

  System:
    OS: macOS 14.3
    CPU: (10) arm64 Apple M1 Max
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.1 - ~/.nvm/versions/node/v20.11.1/bin/node
    Yarn: 1.22.22 - ~/.nvm/versions/node/v20.11.1/bin/yarn
    npm: 10.2.4 - ~/.nvm/versions/node/v20.11.1/bin/npm
    pnpm: 9.1.2 - ~/.nvm/versions/node/v20.11.1/bin/pnpm <----- active
  Browsers:
    Safari: 17.3
  npmPackages:
    @storybook/addon-essentials: ^8.1.10 => 8.1.10 
    @storybook/addon-interactions: ^8.1.10 => 8.1.10 
    @storybook/addon-links: ^8.1.10 => 8.1.10 
    @storybook/addon-onboarding: ^8.1.10 => 8.1.10 
    @storybook/blocks: ^8.1.10 => 8.1.10 
    @storybook/react: ^8.1.10 => 8.1.10 
    @storybook/react-vite: ^8.1.10 => 8.1.10 
    @storybook/test: ^8.1.10 => 8.1.10 
    eslint-plugin-storybook: ^0.8.0 => 0.8.0 
    storybook: ^8.1.10 => 8.1.10

Additional context

I might be missing something or horribly wrong in my approach. Any guidance or suggestions to resolve this issue would be greatly appreciated!

shilman commented 2 weeks ago

Fixed here: https://stackblitz.com/edit/github-iojcfk-hp8kn8?file=package.json

Key points:

  1. The subpath import must match what you're referring to in your code
  2. The storybook key must come before the default key

Do we need to make this more explicit in the docs? @kylegach @kasperpeulen

andrejilderda commented 2 weeks ago

That was indeed the case, thanks @shilman ! I've created a PR for updating the docs here: https://github.com/storybookjs/storybook/pull/28287. Feel free to make changes or close the PR if it’s not needed.

shilman commented 2 weeks ago

@andrejilderda Thanks so much for following up with a docs PR. That's really awesome!!! 🙌