我正在尝试测试以查看在执行此测试时未输入任何输入时它们是否为无列表
App.test.tsx
describe('Should test empty array on onSubmit method',() => {
it('should test empty array onSubmit method', ()=>{
const component = shallow(<App/>)
const form = component.find('Form').at(0);
const preventDefault = jest.fn();
// const items = ['Learn react', 'rest', 'go out'];
// component.setState({
// currentTask:"test-task",
// tasks:[...items, 'test-task']
// })
// form.simulate('submit', { preventDefault });
// expect(preventDefault).toBeCalled();
// form.props().onSubmit();
form.simulate('submit', {preventDefault})
expect(component.state().tasks.length).toBe(0);
})
})
但是我收到这个错误
● 应该在 onSubmit 方法上测试空数组 › 应该在 onSubmit 方法上测试空数组
expect(received).toBe(expected) // Object.is equality Expected: 0 Received: 1
我注意到我有读取这个的 linting 错误
Property 'tasks' does not exist on type 'Readonly<{}>'.
在这条线上
expect(component.state().tasks.length).toBe(0);
我应该改变什么才能通过?
我引用了类似于这个问题的东西
但该解决方案对我不起作用。
应用程序.tsx
import React from 'react';
import logo from './logo.svg';
import Form from './Form';
import './App.css';
// we need an interface to be able to use the state properties, if not error.
// the same rule applies when using props
// so here we call Istate
interface IState {
currentTask: string;
tasks: Array<string>;
}
export default class App extends React.Component<{}, IState>{
constructor(props: {}){
super(props);
this.state = {
currentTask: "",
tasks:[]
}
}
// when using e.preventDefault in typescript, or any paramater, it has to be followed
// by the following any, array, string, etc. in this case we use any
handleSubmit(e: any){
e.preventDefault();
this.setState({
currentTask: "",
tasks: [...this.state.tasks, this.state.currentTask]
}, () => {
console.log(this.state.tasks)
})
}
onChange = (e: any) => {
e.preventDefault();
this.setState({
currentTask: e.target.value
})
}
render(){
return (
<div className="App">
<h1 className="sampleh1">React Typescript Todo</h1>
<Form
onSubmit={(e)=> this.handleSubmit(e)}
currentTask={this.state.currentTask}
onChange={this.onChange}
/>
</div>
);
}
}
边注
如果我更改代码
expect(component.state().tasks.length).toBe(0);
至
expect(component.state().tasks).toHaveLength(0);
我明白了,我很困惑,因为它们在数组中没有值,那么为什么它接收 1 而不是 0 ???
Received array: [""]
该错误是有效的,因为在handleSubmit
代码中,您将空字符串作为元素推送到数组中tasks
,因此长度显示为 1。
this.setState({
currentTask: "",
tasks: [...this.state.tasks, this.state.currentTask]
}
所以在上面的代码执行之后, state.tasks = [""] // 其长度现在将为 1。所以,如果你的目标是推送 currentTask,如果它存在,那么在这里使用一些条件运算符。
this.setState(prevState => ({
currentTask: "",
tasks: prevState.currentTask ? [...prevState.tasks, prevState.currentTask] : prevState.tasks
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句