learnstorybook-code
                                
                                 learnstorybook-code copied to clipboard
                                
                                    learnstorybook-code copied to clipboard
                            
                            
                            
                        Question on component contains smart component doing async call
I wonder how you write storybook for this case
<A>
    <B />
</A>
B is smart component which in its componentDidMount, it fetch data from endpoint using axios or rxjs ajax. How do you intercept the request to return fake data. I do not want it to hit the real endpoint
Hey @dmngu9.
One option is to mock out the library you are using a require-time mock. This is sort of brittle though.
A better option is to have your B component take its async library from the context, e.g. this.context.axios. You can make it default to requiring axios if the context is unset if you want it to be easily consumable. Then you can use a mocked axois provider when testing.
Does anyone else have any other ways to do it?
I had similar situation recently on my mocha test. I used sinon with its sandbox.
Basic idea: the tester (or story in your case) will import the component, and also its referenced component (like axios in your example) with import * as targetsReference from 'target-s-reference', and then stub it.
https://railsware.com/blog/mocking-es6-module-import-without-dependency-injection/
Without sandbox, this injection stays and influences other tests. So make sure you also use stub with sandbox. https://sinonjs.org/releases/v1.17.7/sandbox/ I used sandbox on before() and after(), but since you are doing this for storybook, you could do the same on lifecycle hooks.
I happened to deal with ES6 style (export) and ES5 style (module.exports) mixed, and that also made things tricky. This link was most helpful. https://kentcdodds.com/blog/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution
I hope it helps.