brendangibson
brendangibson

Reputation: 2543

How do I mock a component that has a 'ref' with jest?

I have some code like:

import { GoogleMap } from 'react-google-maps';

const GoogleMapContainer = () => {
    const zoomToBounds = React.useCallback(
        (map): void => map && bounds && map.fitBounds(bounds),
        [bounds]
    );


    <GoogleMap ref={zoomToBounds}>
        ...
    </GoogleMap>
}

and am trying to mock the GoogleMap with jest when I am testing GoogleMapContainer

jest.mock('react-google-maps', () => ({
      GoogleMap: (props) => <div>{props.children}</div>,
}));

However, I get an error like:

    Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

I am unable to use forwardRef because jest complains about using functions from outside the scope. I get the same error if I try to create mock class-based component for GoogleMap.

How do I get around the ref error?

Upvotes: 5

Views: 4139

Answers (1)

brendangibson
brendangibson

Reputation: 2543

In answer to my own question.

You can refer to external variables in your mock if you start their name with mock. Then you can require the containing class after the mock, guaranteeing that the external variable (MockGoogleMap) is set.

class MockGoogleMap extends Component {
  constructor(props) {
    super(props);
  }
  render(): ReactElement {
    return <div>{this.props.children}</div>;
  }
}

jest.mock('react-google-maps', () => ({
  GoogleMap: MockGoogleMap,
}));
const GoogleMapContainer = require('./GoogleMapContainer').default;

Upvotes: 3

Related Questions