I am trying to use react-testing-lib to do some integration testing
I want to mock a function like inside my react class called handleSubmit
handleSubmit(){
// does some stuff
// calls an action creator
}
I basically want to stub this method, so that it either returns null/undefined or anything. But I don't want it to actually call the action creator
The reason being I wanted to assert some UI is present and calling the action creator is giving me the error:
Actions must be plain objects. Use custom middleware for async actions.
I have tried to jest.mock(thismethod) and jest.spyOn()` too but neither seem to work. I just want it to do something like
myFunc() {
}
as if it were an empty function and does nothing. How can I stub this?
It looks like handleSubmit is a prototype method...if it is then you can mock it like this:
import * as React from 'react';
import { render, fireEvent } from 'react-testing-library';
class MyComponent extends React.Component {
handleSubmit() { // <= prototype method
throw new Error('should not get here');
}
render() {
return (<button onClick={this.handleSubmit}>the button</button>);
}
}
test('MyComponent', () => {
const mock = jest.spyOn(MyComponent.prototype, 'handleSubmit');
mock.mockImplementation(() => {}); // <= replace the implementation
const { getByText } = render(<MyComponent/>);
fireEvent.click(getByText('the button'));
expect(mock).toHaveBeenCalled(); // Success!
});
Just make sure to implement the mock on the prototype before rendering the component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With