gpt4 book ai didi

reactjs - Jest TypeError : e. preventDefault 不是函数

转载 作者:行者123 更新时间:2023-12-05 09:13:25 24 4
gpt4 key购买 nike

我正在尝试测试 onSubmit 方法,但我遇到了这个错误。

TypeError: e.preventDefault is not a function

我正在引用这个博客教程

https://medium.com/@aghh1504/6-testing-react-components-using-jest-and-enzyme-b85db96fa1e3

我引用了另一个问题但没有答案

e.preventDefault is not a function - Jest React

App.test.tsx

describe('Should test onSubmit method',() => {
it('should test onSubmit method', ()=>{
const component = shallow(<App/>)
const preventDefault = jest.fn();
const items = ['Learn react', 'rest', 'go out'];
component.setState({
currentTask:"test-task",
tasks:[...items, 'test-task']
})

component.find('form').simulate('submit', preventDefault);
expect(preventDefault).toBeCalled();

})
})

App.tsx

import React from 'react';
import logo from './logo.svg';
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)}>
<input value={this.state.currentTask} type="text" placeholder="enter a todo"
onChange={this.onChange}/>
<button type="submit"> Add Todo</button>
</form>
</div>
);

}
}

最佳答案

尝试将 mockEvent 对象作为第二个参数传递。

component.find('form').simulate('submit', { preventDefault });

关于reactjs - Jest TypeError : e. preventDefault 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com