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?

2 Answers

0
brian-lives-outdoors On

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.

0
Shruti On

Try below mocking of function and action:

//Mock function
 var mockPromise = new Promise((resolve, reject) => {
    resolve(<mock response similar to actual promise response>);
});
functionName = jest.fn().mockReturnValueOnce(mockPromise)

//Mock action
const actions = [];
const dispatchAction = jest.fn((dispatchCall) => {
      actions.push(dispatchCall);
});

functionName()(dispatchAction);
expect(dispatchAction).toBeCalledTimes(1)