Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question on component contains smart component doing async call #5

Open
dmngu9 opened this issue Sep 14, 2018 · 2 comments
Open

Question on component contains smart component doing async call #5

dmngu9 opened this issue Sep 14, 2018 · 2 comments

Comments

@dmngu9
Copy link

dmngu9 commented Sep 14, 2018

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

@tmeasday
Copy link
Member

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?

@kennethchoe
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants