Search code examples
reactjsstorybook

Storybook override import method


My component 'ReportWrapper' is something like below where it import 'getReportData' which in turn return data async.

import { getReportData } from "../dataFecther";

export const ReportWrapper = ({ query }) => { 
  const { data, loading, error } = getReportData({ type: "1", query });
  return (
    <ReportTable
      reportData={data}
      error={error}
    />
  ); 

The way it fetch data may not be suitable for writing Storybook stories. Is there a way to override this import of 'getReportData' to something like a mock import in stories.

Sample story

export default {
  title: "Storybook",
  component: ReportWrapper,
  // More on argTypes: https://storybook.js.org/docs/react/api/argtypes
}; 
const Template = ({ args }) => {
  return (
      <ReportWrapper {...args} />
  );
};

export const First = Template.bind({}); 
First.args = {
  storyName: "First One",
};

Solution

  • If I understand correctly you want to use a different getReportData in stories. I read this as mocking a module in stories.

    I managed to do this using Storybook's webpackFinal config and to add a webpack plugin - webpack's NormalModuleReplacementPlugin. Basically you can replace a module in stories using this approach.

    You could try this in your storybook config:

    module.exports = {
      webpackFinal: async (config, { configType }) => {
        config.plugins.push(
          new webpack.NormalModuleReplacementPlugin(
            /some\/path\/to\/dataFetcher\.js/,
            path.join(__dirname, 'mockedDataFetcher.js')
          )
        );
      }
    }