Why do I keep on getting 'Received number of calls: 0' error in my React unit test?

Viewed 1153

I'm new to React unit test, I keep on getting error: Received number of calls: 0 when trying to test that the handleSubmit method is called on form submission:

error:

    Expected number of calls: 1
    Received number of calls: 0

       9 |     const form = wrapper.find('form');
      10 |     form.simulate('submit');
    > 11 |     expect(onSubmitFn).toHaveBeenCalledTimes(1);

Form.test.js:

import React from "react";
import {shallow } from 'enzyme';
import Form from './Form';

it('calls handleSubmit function on form submission', () => {
    const onSubmitFn = jest.fn();
    const wrapper = shallow(<Form onSubmit={onSubmitFn} />);
    const form = wrapper.find('form');
    form.simulate('submit');
    expect(onSubmitFn).toHaveBeenCalledTimes(1);
})

Form.js:

import React from 'react';

class Form extends React.Component {

    render() {
        return (
            <form onSubmit={this.props.handleSubmit}>
                <div>
                    <div className="field">
                        <label className="label">Postcode</label>
                            <input className="input" type="text" onChange={this.props.handleInputChange} required />
                    </div>
                    <div className="field">
                        <div className="control">
                            <input type='submit' value='Search' />
                        </div>
                    </div>
                </div>
            </form>
        )
    }
}

export default Form;

Tile.js which includes Form.js:

import React from 'react';
import Form from './Form';

class Tile extends React.Component {
    .
    .
    .
    handleSubmit(e) {
        e.preventDefault();
        if (this.handleValidation()) {
            this.getCoord();
            this.setState({ error: false })
        }
        else {
            this.setState({ error: true });
        };
    }
    .
    .
    .
render() {
        return (
            <div>
                <Form handleSubmit={this.handleSubmit}/>
            </div>
        )
}

Any help?

1 Answers

The prop is called handleSubmit:

<form onSubmit={this.props.handleSubmit}>

It should be:

shallow(<Form handleSubmit={onSubmitFn} />);
Related