Reputation: 1255
So I'm trying to test if the handle submit function is being called on my form. It's hitting the condition shown below and preventing the form from being submitted. How would I go about mocking the validate function inside to return an empty object {}. This would make my form valid and then submit it as required.
Validate is defined outside of the Form component in form.jsx . I'm exporting it just as export const validate = {}
handleSubmit = event => {
const {args} = this.state;
let errors = validate(args);
const isValid = isEmpty(errors)
if(!isValid) {
this.setState({args: args})
event.preventDefault()
}
this.setState({args: args})
}
My attempt
it('should handleSubmit when form is submitted', () => {
const fakeValidate = { validate: () => true };
const handleSubmit = jest.fn().mockImplementation((cb) => () => cb({ test: 'test' }));
const wrapper = shallow(<Form form="test" onSubmit={handleSubmit}/>);
wrapper.find('form').simulate('submit', fakeValidate);
expect(handleSubmit).toBeCalledTimes(1);
});
Thanks!
Upvotes: 4
Views: 5806
Reputation: 223259
It's not possible to mock a function that is defined in the same module it's used. In order to be mockable, it should be either imported from another module and mocked with jest.mock
, or be used as a method on some object and mocked with jest.spyOn
.
Since it's used with class component, it can be defined as a method:
validate() {...}
handleSubmit = event => {
...
let errors = this.validate(args);
...
}
And be mocked either on the class:
jest.spyOn(Form.prototype, 'validate').mockReturnValue(...);
Or component instance:
jest.spyOn(wrapper.instance(), 'validate').mockReturnValue(...);
In case validate
is reusable or used with functional component, it should moved to another module.
Upvotes: 2