johns221b
johns221b

Reputation: 35

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",
};

Upvotes: 3

Views: 3454

Answers (2)

Arash Ghazi
Arash Ghazi

Reputation: 1001

If I understand correctly, you want to run a method inside of a component which that method comes from another component.

the first component that wants to take the method from outside

const FirstComponent = ({getReportData}) => {
  const [data,setData]=useState();
  useEffect(()=>{
    const fetchData=async()=>{
      if(getReportData){
        let response = getReportData();
        if(response.status === 200)
          setData(response.data)
      }
    }
    fetchData();
  })
  return (
    <div>
      {data}
    </div>
  );
};

and the second component that to use the first component


const SecondComponent = () => {
  const axiosTest=async()=> {
    let response = await axios.get("ajax/api/..")
    setData(response.data)
}
  return (
    <FirstComponent getReportData={axiosTest} />
  );
};

Upvotes: 1

bamse
bamse

Reputation: 4383

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')
      )
    );
  }
}

Upvotes: 4

Related Questions