您如何使用Jest测试React组件中的功能?

时间:2019-07-30 18:28:17

标签: reactjs typescript jestjs material-ui enzyme

如何在我的文本字段组件中测试strictMaxLength?它称为onInput,我想检查它是否返回正确的值。我如何在玩笑测试中调用strictMaxLength?

export default function StoreIDTextField(props: any) {
  const { onValueChanged } = props;
  // @ts-ignore
  const classes:any = useStyles();
  const [values, setValues] = React.useState<State>({
    name: 'Cat in the Hat',
    age: null,
  });

  // eslint-disable-next-line no-unused-vars
  const handleChange = (name: keyof State) => (event: React.ChangeEvent<HTMLInputElement>) => {
    setValues({ ...values, [name]: event.target.value });
    onValueChanged(event.target.value);
  };

  function restrictMaxLength(e: any) {
    return Math.max(0, parseInt((e.target as HTMLInputElement).value)).toString().slice(0, 3);
  }

  return (
    <form className={classes.container} noValidate autoComplete="off">
      <TextField
        type="number"
        onInput={(e) => {
          // restricts maxLength of store number to 3 digits
          // eslint-disable-next-line max-len,radix
          (e.target as HTMLInputElement).value = restrictMaxLength(e);
        }}
        required
        id="outlined-number"
        onChange={handleChange('age')}
        value={values.age}
        label="Store ID"
        defaultValue=""
        className={classes.textField}
      />
    </form>
  );
}

enter image description here

0 个答案:

没有答案
相关问题