首页 > 解决方案 > TypeError:使用 React、Storybook 和 Storyshots 插件进行快照测试时,提供的值不是“元素”类型

问题描述

我在下面测试我的IndeterminateCheckbox组件时收到``错误:

import { Checkbox } from '@chakra-ui/core';
import React from 'react';

export interface IndeterminateCheckboxProps {
  indeterminate: boolean;
  checked: boolean;
  title: string;
  onChange: () => void;
}

const IndeterminateCheckbox = React.forwardRef(
  (
    { indeterminate, checked, title, onChange }: IndeterminateCheckboxProps,
    forwardedRef: any
  ): JSX.Element => {
    return (
      <Checkbox
        colorScheme="brand.blue"
        isIndeterminate={indeterminate}
        isChecked={checked}
        onChange={onChange}
        name={title}
        sx={{ mt: '4px', borderColor: 'brand.grey.100' }}
      />
    );
  }
);

export default IndeterminateCheckbox;

我正在使用带有以下故事的 Storyshots 插件进行快照测试:

/* eslint-disable react/jsx-props-no-spreading */
import React from 'react';
import { Meta, Story } from '@storybook/react/types-6-0';
import IndeterminateCheckbox, {
  IndeterminateCheckboxProps,
} from './IndeterminateCheckbox';

export default {
  title: 'IndeterminateCheckbox',
  component: IndeterminateCheckbox,
  argTypes: {
    indeterminate: {
      control: {
        type: 'boolean',
      },
    },
    checked: {
      control: {
        type: 'boolean',
      },
    },
    title: {
      control: {
        type: 'string',
      },
    },
  },
} as Meta;

const Template: Story<IndeterminateCheckboxProps> = args => (
  <IndeterminateCheckbox {...args} />
);

export const Unchecked = Template.bind({});
Unchecked.args = {
  indeterminate: false,
  title: 'unchecked',
  checked: false,
  onChange: () => null,
};

export const Checked = Template.bind({});
Checked.args = {
  indeterminate: false,
  title: 'checked',
  checked: true,
  onChange: () => null,
};

export const Indeterminate = Template.bind({});
Indeterminate.args = {
  indeterminate: true,
  title: 'indeterminate',
  checked: false,
  onChange: () => null,
};

有什么想法可能导致这种情况吗?

标签: reactjsjestjssnapshotstorybookstoryshots

解决方案


您必须更新 storyshots 配置以支持将 refs 传递给它们的元素:

react-test-renderer 不为渲染的组件提供参考。默认情况下,当引用 refs 时它返回 null。为了模拟依赖 refs 的元素,你必须使用从 15.4.0 版本开始添加到 React 的 createNodeMock 选项。 https://www.npmjs.com/package/@storybook/addon-storyshots#using-createnodemock-to-mock-refs


推荐阅读