不是更改输入酶,而是使用未定义的键和im试图插入的值将新变量插入到TaskForm状态。 我的结果看起来像这样
期望值等于: {“描述”:“新任务描述”,“ id”:“”,“标题”:“新任务”} 收到: {“ description”:“”,“ id”:“”,“ title”:“”,“ undefined”:“新任务”}
import React, { Component } from 'react';
const uuidv4 = require('uuid/v4')
//This is my component
class TaskForm extends Component {
state = {
title: '',
description: '',
id:''
};
onChange = e => this.setState({ [e.target.name]: e.target.value });
resetForm = () => {
this.setState({
title:'',
description:''
})
}
onSubmit = e => {
e.preventDefault()
const task = this.state
if(this.props.editTask){
this.props.editTaskFunc(this.state)
}else{
this.setState(prevstate => ({
id:uuidv4()
}))
this.props.addTask(this.state)
}
this.resetForm()
this.props.closeToggle()
}
componentDidMount = () => {
if(this.props.editTask){
const {id,title,description} = this.props.editTask
this.setState(
prevState => ({
id,
title,
description
})
);
}
}
render() {
const { title, description } = this.state;
return (
<form className="task-form" onSubmit={this.onSubmit}>
<input name="title" placeholder="Enter task title" type="text" value={title} onChange={this.onChange} required/>
<input name="description" placeholder="Enter task description" type="text" value={description} onChange={this.onChange} required />
<button>Submit</button>
<button id="reset-btn" type="button" onClick={this.resetForm}>Reset</button>
</form>
);
}
}
export default TaskForm;
//This is my test
import React from 'react';
import ReactDOM from 'react-dom';
import TaskForm from './TaskForm';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16'
configure({adapter: new Adapter()});
const taskForm = shallow(<TaskForm/>)
describe('<TaskForm/>',() => {
it('renders without crashing', () => {
expect(taskForm).toMatchSnapshot()
});
it('renders state inital empty array called tasks ', () => {
expect(taskForm.state()).toEqual({
title: '',
description: '',
id:''
})
});
describe('entering input and reseting <TaskForm/> state',() => {
beforeEach(() => {
// taskForm.find("[name='title']").simulate('change',{target:{value:"new task"}})
// taskForm.find("[name='description']").simulate('change',{target:{value:"new task description"}})
taskForm.find("[name='title']").simulate('change',{target:{value:"new task"}})
})
afterEach(() => {
taskForm.setState({
title: '',
description: '',
id:''
})
})
it('<TaskForm/> should have changed state',() => {
expect(taskForm.state()).toEqual({
title: 'new task',
description: 'new task description',
id:''
})
})
// it('resets <TaskForm/> state on click',() => {
// taskForm.find('#reset-btn').simulate('click')
// expect(taskForm.state()).toEqual({
// title: '',
// description: '',
// id:''
// })
// })
})
})
答案 0 :(得分:0)
taskForm.find("[name='title']").simulate('change',{target:{value:"new task"}})
})
应该是
taskForm.find("[name='title']").simulate('change',{target:{value:"new task", name:'title'}})
})
在模拟中,您需要从事件对象传递您正在使用的所有属性。