React Storybook通过args传递函数测试组件状态切换问题咨询
问题原因
你的组件属于受控组件,ecoDesigned状态完全由父层传入的prop决定,你当前Storybook配置中给setEcoDesigned配置的action: 'clicked'仅用来记录点击事件日志,不会实际更新Storybook管理的ecoDesigned参数值,所以点击按钮后prop没有变化,组件自然不会触发对应交互反馈,并非Storybook不支持这类测试场景。
解决方案
方案1:使用Storybook内置useArgs钩子更新参数(推荐)
这是最符合Storybook使用规范的写法,修改后story文件代码如下:
import React from 'react'; import { ComponentStory, ComponentMeta } from '@storybook/react'; import { useArgs } from '@storybook/client-api'; import { ModelCard } from './'; export default { title: 'ModelCard', component: ModelCard, argTypes: { yearProduct: { control : 'text'}, ecoDesigned: { control: 'boolean'}, titleProduct: {control: 'text'}, photoProduct: {control: 'text'}, } } as ComponentMeta<typeof ModelCard>; const Template: ComponentStory<typeof ModelCard> = (args) => { const [_, updateArgs] = useArgs(); const handleSetEcoDesigned = (val: boolean) => { updateArgs({ ecoDesigned: val }); }; return <ModelCard {...args} setEcoDesigned={handleSetEcoDesigned}/>; }; export const ModelCardCompleteControls = Template.bind({}); ModelCardCompleteControls.args = { yearProduct: '2018', ecoDesigned: false, titleProduct: '66180 - W200 S | 1019507 - ATHLLE Watches or Stopwatche 7026 2021 | GEDS', photoProduct: 'https://picsum.photos/200', };
修改后点击按钮时,Storybook控制面板里的ecoDesigned布尔值会同步更新,组件也会对应切换样式,完全满足交互测试需求。如果需要保留点击事件日志,可以在handleSetEcoDesigned方法内自行添加action日志输出。
方案2:在故事内部维护本地状态模拟父组件行为
如果不需要同步Storybook控制面板的参数值,也可以直接在Template内用React useState模拟父组件的状态管理,写法如下:
const Template: ComponentStory<typeof ModelCard> = (args) => { const [ecoDesigned, setEcoDesigned] = React.useState(args.ecoDesigned); return <ModelCard {...args} ecoDesigned={ecoDesigned} setEcoDesigned={setEcoDesigned}/>; };
内容的提问来源于stack exchange,提问作者Antoine Deloy
相关产品推荐
相关产品推荐

