开玩笑的TypeError:e.preventDefault不是函数

时间:2019-05-23 01:35:46

标签: reactjs typescript jestjs enzyme

我正在尝试测试onSubmit方法,但是却收到此错误。

  

TypeError:e.preventDefault不是函数

我正在引用此博客教程

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>
    );

  }
}

3 个答案:

答案 0 :(得分:1)

simulate的第二个参数是当您调用onSubmit时传递给处理程序的模拟事件,因此它必须采用处理程序期望的事件对象的形式:

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

同样,如果要测试onChange函数,则需要将target/value作为simulate的第二个参数传递一个模拟事件:

component.find('input').simulate('change', { target: { value: 'todo' } });

答案 1 :(得分:1)

尝试将模拟事件对象作为第二个参数传递。

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

答案 2 :(得分:1)

如果您使用Jest

form.simulate(`submit`, {preventDefault: jest.fn()});

,或者如果没有,则为空函数

form.simulate(`submit`, {preventDefault: () => {}});