最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Issue with Interaction Tests for Controlled Components in React Storybook - Stack Overflow

programmeradmin1浏览0评论

I am using React Storybook to show examples of a TextInput component in React. The component has value and onValueChange props to handle the component's state.

As it is a controlled component, I added a decorator to the story meta so that the onValueChange prop updates the args of the story using useArgs hook (see /)

const meta = {
  title: '2. Components/Basic/TextInput',
  component: TextInput,
  tags: ['autodocs'],
  decorators: [
    
    function Component(Story, ctx) {
      const [, setArgs] = useArgs<typeof ctx.args>();

      const onValueChangeWithArgUpdate = (value: string) => {
        ctx.args.onValueChange?.(value);
        setArgs({ value });
      };

      return (
        <Story
          args={{ ...ctx.args, onValueChange: onValueChangeWithArgUpdate }}
        />
      );
    },
  ],
} satisfies Meta<typeof TextInput>;

This works well, however I also have an interaction test whenever the story is viewed - it enters some text and verifies that the onValueChange function is called the correct number of times.

If the line setArgs({ value }) is commented out then the interaction test still works (albeit the entered test does not appear in the input the component has no internal state). Otherwise, the result is "onValueChanged has been called 0 times" in Storybook.

Please could someone explain why the test is failing and if there is a way to fix it. I tried wrapping onValueChangeWithArgUpdate in a useCallback hook but it did not help.

发布评论

评论列表(0)

  1. 暂无评论