Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest TypeError: e.preventDefault is not a function

I'm trying to test the onSubmit method, however im getting this error.

TypeError: e.preventDefault is not a function

I'm referencing this blog tutorial

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

i referenced another question but no answer

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

  }
}
like image 498
randal Avatar asked Apr 14 '26 04:04

randal


2 Answers

Try passing mockEvent object as second argument.

component.find('form').simulate('submit', { preventDefault });
like image 123
Rikin Avatar answered Apr 15 '26 23:04

Rikin


If you using Jest

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

or just an empty function if you don't

form.simulate(`submit`, {preventDefault: () => {}});
like image 22
MagicWizard Avatar answered Apr 16 '26 01:04

MagicWizard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!