Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 测试自定义Textfield材质UI组件未触发更改事件_Reactjs_Unit Testing_Material Ui_Enzyme - Fatal编程技术网

Reactjs 测试自定义Textfield材质UI组件未触发更改事件

Reactjs 测试自定义Textfield材质UI组件未触发更改事件,reactjs,unit-testing,material-ui,enzyme,Reactjs,Unit Testing,Material Ui,Enzyme,我试图测试自定义材质UI textfield组件,但未触发更改事件,测试失败,收到的值与初始状态相同 这是我得到的错误: 预期:“新评论” 收到:“” 很明显,该值没有更改,也没有触发更改事件 这是包含组件的表单: import React, { useState } from "react"; import { connect } from "react-redux"; import { makeStyles, useTheme, withStyles } from "@material-ui

我试图测试自定义材质UI textfield组件,但未触发更改事件,测试失败,收到的值与初始状态相同

这是我得到的错误:

预期:“新评论” 收到:“”

很明显,该值没有更改,也没有触发更改事件

这是包含组件的表单:

import React, { useState } from "react";
import { connect } from "react-redux";
import { makeStyles, useTheme, withStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles(theme => ({
  btn: {
    ...theme.typography.submitBtn,
    width: "100%",
    "&:hover": {
      background: theme.palette.common.whiteColor,
      color: theme.palette.common.mainBlue,
      border: "1px solid #4f34ff",
    },
  },
}));

const CssTextField = withStyles(theme => ({
  root: {
    "& label.Mui-focused": {
      color: theme.palette.common.mainBlue,
    },
    "& .MuiInput-underline:after": {
      borderBottomColor: theme.palette.common.mainBlue,
    },
    "& .MuiOutlinedInput-root": {
      "& fieldset": {
        borderColor: theme.palette.common.mainBlue,
      },
      "&:hover fieldset": {
        borderColor: theme.palette.common.mainBlue,
      },
      "&.Mui-focused fieldset": {
        borderColor: theme.palette.common.mainBlue,
      },
    },
  },
}))(TextField);

export const PostForm = ({ onSubmit, auth, post }) => {
  const [values, setValues] = useState({
    title: post ? post.title : "",
    body: post ? post.body : "",
  });
  const [errors, setErrors] = useState({
    titleError: "",
    bodyError: "",
  });
  const { title, body } = values;
  const { titleError, bodyError } = errors;
  const classes = useStyles();
  const theme = useTheme();

  const onChange = event => {
    let valid;
    switch (event.target.id) {
      case "title":
        setValues({ ...values, title: event.target.value });
        valid = /^$/.test(event.target.value);
        if (valid) {
          setErrors({ ...errors, titleError: "Title required" });
        } else {
          setErrors({ ...errors, titleError: "" });
        }
        break;
      case "body":
        setValues({ ...values, body: event.target.value });
        valid = /^$/.test(event.target.value);
        if (valid) {
          setErrors({
            ...errors,
            bodyError: "Post is required",
          });
        } else {
          setErrors({ ...errors, bodyError: "" });
        }
        break;
      default:
        break;
    }
  };

  const onSubmitForm = e => {
    e.preventDefault();
    const postData = {
      ...values,
      postedBy: auth.user.name,
    };
    onSubmit(postData);
  };

  return (
    <div>
      <Grid container>
        <Grid
          item
          container
          direction="column"
          spacing={2}
          style={{ width: "75vw", margin: "0 auto" }}
        >
          <Grid item>
            <CssTextField
              error={!!titleError}
              helperText={titleError}
              className={classes.margin}
              label="Title"
              variant="outlined"
              id="title"
              fullWidth
              InputProps={{
                className: classes.inputColor,
              }}
              InputLabelProps={{
                style: {
                  color: theme.palette.common.mainBlue,
                },
              }}
              onChange={onChange}
              value={title}
              // inputProps={{ style: { fontFamily: 'nunito', color: 'white'}}}
            />
          </Grid>
          <Grid item>
            <CssTextField
              error={!!bodyError}
              helperText={bodyError}
              className={classes.margin}
              label="Enter your post here..."
              variant="outlined"
              id="body"
              fullWidth
              multiline
              rows={10}
              InputProps={{
                className: classes.inputColor,
              }}
              InputLabelProps={{
                style: {
                  color: theme.palette.common.mainBlue,
                },
              }}
              onChange={onChange}
              value={body}
              // inputProps={{ style: { fontFamily: 'nunito', color: 'white'}}}
            />
          </Grid>
          <Grid item>
            <Button
              className={classes.btn}
              onClick={onSubmitForm}
              disabled={!!titleError || !title || !!bodyError || !body}
            >
              Submit
            </Button>
          </Grid>
        </Grid>
      </Grid>
    </div>
  );
};

const mapStateToProps = state => ({
  auth: state.auth,
});
export default connect(mapStateToProps)(PostForm);
import React,{useState}来自“React”;
从“react redux”导入{connect};
从“@material ui/core/styles”导入{makeStyles,useTheme,withStyles}”;
从“@material ui/core/Grid”导入网格;
从“@物料界面/核心/按钮”导入按钮;
从“@material ui/core/TextField”导入TextField;
const useStyles=makeStyles(主题=>({
btn:{
…主题.版式.提交,
宽度:“100%”,
“&:悬停”:{
背景:theme.palette.common.whiteColor,
颜色:theme.palette.common.Main蓝色,
边框:“1px实心#4f34ff”,
},
},
}));
const CssTextField=带有样式(主题=>({
根目录:{
“&label.Mui聚焦”:{
颜色:theme.palette.common.Main蓝色,
},
“&.MuiInput下划线:之后”:{
borderBottomColor:theme.palette.common.Main蓝色,
},
“&.muioOutlinedInput根”:{
“&字段集”:{
边框颜色:theme.palette.common.Main蓝色,
},
“&:悬停字段集”:{
边框颜色:theme.palette.common.Main蓝色,
},
“&.Mui聚焦字段集”:{
边框颜色:theme.palette.common.Main蓝色,
},
},
},
}))(文本字段);
export const PostForm=({onSubmit,auth,post})=>{
const[values,setValues]=useState({
标题:post?post.title:“”,
正文:post?post.body:“”,
});
常量[errors,setErrors]=useState({
标题错误:“”,
正文错误:“”,
});
常量{title,body}=值;
常量{titleError,bodyError}=错误;
const classes=useStyles();
const theme=useTheme();
const onChange=事件=>{
让有效;
开关(event.target.id){
案例“标题”:
setValues({…值,标题:event.target.value});
valid=/^$/.test(event.target.value);
如果(有效){
setErrors({…errors,titleError:“Title required”});
}否则{
setErrors({…errors,titleError:});
}
打破
案例“正文”:
setValues({…values,body:event.target.value});
valid=/^$/.test(event.target.value);
如果(有效){
设置错误({
…错误,
bodyError:“需要发布”,
});
}否则{
setErrors({…errors,bodyError:});
}
打破
违约:
打破
}
};
const onSubmitForm=e=>{
e、 预防默认值();
常量postData={
价值观
postedBy:auth.user.name,
};
onSubmit(postData);
};
返回(
提交
);
};
常量mapStateToProps=状态=>({
auth:state.auth,
});
导出默认连接(MapStateTops)(PostForm);
这项测试:

import React from "react";
import { createMount } from "@material-ui/core/test-utils";
import { PostForm } from "../../components/Post/PostForm";

describe("Post Form", () => {
  let mount;

  beforeEach(() => {
    mount = createMount();
  });

  afterEach(() => {
    mount.cleanUp();
  });

  it("should set title on input change", () => {
    const wrapper = mount(<PostForm />);

    wrapper
      .find("#title")
      .at(0)
      .simulate("change", {
        target: { value: "New Comment" },
      });
    wrapper.update();

    expect(wrapper.find("#title").at(0).prop("value")).toEqual("New Comment");
  });
});
从“React”导入React;
从“@material ui/core/test utils”导入{createMount}”;
从“../../components/Post/PostForm”导入{PostForm}”;
描述(“发布表单”,()=>{
让我们登上;
在每个之前(()=>{
mount=createMount();
});
之后(()=>{
mount.cleanUp();
});
它(“应在输入更改时设置标题”,()=>{
const wrapper=mount();
包装纸
.查找(“标题”)
.at(0)
.模拟(“改变”{
目标:{value:“新注释”},
});
wrapper.update();
expect(wrapper.find(“#title”).at(0.prop(“value”)).toEqual(“新评论”);
});
});
您是否尝试过在(0)处查找(#title”).at.dive().simulate(..)失败,您可以尝试让您的测试首先使用文本字段,然后尝试您的自定义字段..您是否尝试过在(0)处查找(#title”).at.dive().simulate(..)失败,您可以尝试让您的测试首先使用文本字段,然后尝试您的自定义字段。。