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

Expose a mocking API #14873

Open Meemaw opened 3 years ago

Meemaw commented 3 years ago

Is your feature request related to a problem? Please describe When building components, one would like to mock some things to visualize components in some edge cases. For example, imagine I have a useWidth react hook that is using IntersectionObserver under the hood. I would like to test this component under the SSR circumstances (where width === 0) to see how it behaves (without convoluting its props just for that purpose).

In past I've been using decorators + sinon.sandbox  to somehow set this up https://github.com/insights-io/Insight/blob/master/frontend/shared/storybook/src/decorators/mockDecorator.ts, but this setup for some reason doesn't work in all environments (e.g. CRA, NextJS, custom webpack,...)

Describe the solution you'd like I would like storybook to expose some kind of mocking API that would reliably work in all environments. It can be just a decorator.

Example API using sinon:

Story.decorators = [mockDecorator(sandbox => {
   sandbox.stub(MyModule, 'x').returns(0)
})]

Describe alternatives you've considered As mentioned, I've tried my own implementations for this problem, but they are not reliable. I assume internally you have more control over the require mechanism and can implement this more reliably.

Are you able to assist to bring the feature to reality? Maybe

shilman commented 3 years ago

So far we haven't looked into making this part of core. There are some great addons for mocking at the network level, such as https://storybook.js.org/addons/msw-storybook-addon/ as well as addons for axios, apollo client, etc. Ideally the functionality you're describing would first be introduced as an addon, and then potentially be brought into core once it's baked. It certainly seems like a generally useful feature for all frameworks and a variety of use cases!

dessskris commented 3 years ago

Upvote ⬆️

We should also be able to mock a child component that's used in the component we want to showcase in the story

e.g. the story is for <Parent /> but the implementation of Parent uses <Child /> we should be able to mock Child in Parent's story

FranCarstens commented 1 month ago

Great to see some traction on this. It would certainly help us mock child components that contain 3rd party plugins we don't want to load in stories.