I am trying to write a test that uses enzyme to simulate a button click which expects the onClick handler to be fired. I want to replace the component's onClick handler with a mock. When the test runs, the component class method is being called instead of the mock function. Any guidance would be appreciated!
Below is the test output:
FAIL src/Form.test.js
● Console
console.log src/Form.js:5
this is from the component
● Submit handler called on click
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
14 | submitButton.simulate("click");
15 |
> 16 | expect(onHandleSubmitMock).toHaveBeenCalled();
| ^
17 | });
18 |
at Object.<anonymous>.test (src/Form.test.js:16:30)
package versions: "jest": 25.1.0 "jest-enzyme": 7.1.2 "react": 16.8.6
Form.js Component
import React, { Component } from "react";
export class Form extends Component {
onHandleSubmit = () => {
console.log("this is from the component");
};
render() {
return (
<div>
<button data-test="submit" onClick={this.onHandleSubmit}>
Submit
</button>
</div>
);
}
}
export default Form;
Form.test.js
import React from "react";
import { shallow } from "enzyme";
import Form from "./Form";
test("Submit handler called on click", () => {
const onHandleSubmitMock = jest.fn(() => console.log("mock was called"));
const wrapper = shallow(<Form />);
wrapper.instance().onHandleSubmit = onHandleSubmitMock;
wrapper.update();
const submitButton = wrapper.find(`[data-test="submit"]`);
submitButton.simulate("click");
expect(onHandleSubmitMock).toHaveBeenCalled();
});
console.log
). – jonrsharpe