So I am trying to mock a helper function that is nested within other helper functions, using Jest.
The basic structure of the function I actually want to test is like this
import matrixClient from '@mapbox/mapbox-sdk/services/matrix';
// I want to test this function which uses several other helpers
export const getOrderEstimate = async (start, end) => {
// other non-delivery estimate stuff
const deliveryEstimate = await getDeliveryEstimate(start, end);
return {
...otherStuff
delivery: deliveryEstimate
}
}
const getDeliveryEstimate = async (start, end) => {
try {
return await functionThatWrapsMapBox(start, end);
} catch(error) {
// return error
}
}
const functionThatWrapsMapBox = async (start, end) => {
return matrixClient({ accessToken: MAPBOX_TOKEN })
.getMatrix({
points: [{ coordinates: start }, { coordinates: end }],
profile: `driving-traffic`,
})
.send();
}
In my test file I am trying to do something like this,
import * as helpers from './order-estimates';
describe('order estimates', () => {
test('delivery estimates should never be null', () => {
const mockMapBox = jest.spyOn(helpers, 'functionThatWrapsMapBox');
mockMapBox.mockReturnValue(() => ...mockedReturn))
// this function always uses the real implementation of functionThatWrapsMapBox
const orderEstimates = helpers.getOrderEstimate(startAddress, endAddress);
expect(orderEstimates.delivery).not.toBeNull();
});
});
I have tried several manual mocking techniques using jest.mock
and I can only get the mock implementation to fire if I call it directly in my test file which isn't really what I want. I am thinking the jest.spyOn
method is more appropriate but no luck yet.