how can I mock a component when I make a storyBook?

Viewed 26

I'm making a storyBook out of a component that we'll call ParentComponent, it has a child called ChildComponent.

Inside ChildComponent there is a function that makes a call to the code of another repository so this is where the storybook fails.

components: {
  DataProvider:  () => import("common-data-provider"),// --> problem this line
}

How can I mock ChildComponent and not make this request?

StoryBook of Parent Component

  import articlesFunds from "../__fixtures__/articles.json";

    export default {
        component: ParentComponent,
        argTypes: {
            getConfigFilesDataProvider: {
                control: "object",
            },
        },
        args: {
            getConfigFilesDataProvider: () => new Promise((resolve) => setTimeout(() => resolve({ data: articlesFunds }))),
        },
    };

    export const Default = (args) => ({
        components: { ParentComopnent },
        props: Object.keys(args),
        template: `
            <ParentComopnent
            :data-provider="getConfigFilesDataProvider"
            />
        `,
    });

ChildComponent

   <template>
            <DataProvider :data="articles" />
            
    </template>

    <script>
    export default {
        name: "ChildComponent",
        components: {
            DataProvider:  () => import("common-data-provider"),// --> problem this line
            ComponentB
        },
        props: {
            articles: {
                type: Array,
                required: true,
            },
        }
    };
    </script>
1 Answers

Storybook doesn't specifically provide the support for module mocking, but it's possible to use Webpack aliases for that.

Dependency injection of any kind can be used to modify the behaviour of a component in uncommon conditions, e.g. the ability to provide custom component:

    props: {
        articles: {
            type: Array,
            required: true,
        },
        dataProvider: {
           type: null,
           default: () => import("common-data-provider"),
        }
    }

And used like dynamic component:

<component :is="dataProvider" :data="articles"/>

Then custom implementation can be provided through dataProvider prop.

Related