Over a million small businesses, and their advisors are looking for the best cloud apps that integrate with Xero. Partner with us, and we’ll make sure they find yours.

The other day I was looking for snippet to copy and paste which would allow me to mock a higher order component with jest.mock.

Here is theexport default statement my component that is using the HOC. As you can see it’s using a HOC that provides geolocation information from the users browser. LocationState is my component that uses this information:

export default geolocated({
positionOptions: {
enableHighAccuracy: false
},
watchPosition: true,
userDecisionTimeout: 15000
})(LocationState);

Below is the snippet for mocking the HOC in your tests:

jest.mock("react-geolocated", () => {
return {
geolocated: function(hocConf) {
return function(component) {
component.defaultProps = {
...component.defaultProps,
isGeolocationAvailable: true,
isGeolocationEnabled: true,
coords: {
accuracy: 130,
altitude: null,
altitudeAccuracy: null,
heading: null,
latitude: 10,
longitude: 10,
speed: null
}
};
return component;
};
}
};
});

Setting component.defaultProps will set the props that the HOC will pass into your component. An important thing to note. If you want the mocked HOC to pass down the props it itself was passed then you will need to include that when setting defaultProps this is the ...component.defaultProps line.

An generic version of this would look something like:

jest.mock("hoc-module", () => {
return {
hocFunction: function(hocConf) {
return function(component) {
component.defaultProps = {
...component.defaultProps,
mockPropKey: mockPropValue
};
return component;
};
}
};
});

hocConf is the values passed into the HOC from your exported component.

Hope this helps someone wanting a quick snippet.

--

--