I am getting crazy on mocking with Jest. I feel that I have a fairly simple case that I cannot get to work.
I have a service extensions.service
with a bunch of functions:
async function getSplitCost() {
// Check if feature is enabled for the customer
const isEnabled = await isExtensionFeatureEnabled().catch(err => {
throw new Error(err);
});
return {
split_cost: [],
feature_enabled: isEnabled
}
}
async function isExtensionFeatureEnabled(): Promise<boolean> {
console.log('Function is executed');
let serviceStatus = await servicesService.getServiceStatus('service1').catch( err => {
throw new Error(err.message);
});
return serviceStatus;
}
export default {
getSplitCost,
isExtensionFeatureEnabled,
};
I now want to create a test case that should validate the function getSpitCost and mock the response from isExtensionFeatureEnabled without running the function. Example that I have tried below:
jest.mock('../services/extensions.service', () => ({
__esModule: true,
...jest.requireActual('../services/extensions.service'),
isExtensionFeatureEnabled: jest.fn().mockResolvedValue(false),
}));
import extensionsService from "../services/extensions.service";
describe("getSpitCost", () => {
it("should return empty split cost when extension feature is disabled", async () => {
const result = await extensionsService.getSplitCost();
expect(result).toEqual({
split_cost: [],
feature_enabled: false
});
});
});
As I am not calling the function isExtensionFeatureEnabled directly I cannot use spyOn. However, even though I mock the response to false the actual function is being executed. The extension service contains a lot of more functions that are being tested in the same test file, so I cannot mock everything. Also, I cannot split up the two functions to separate files.
How should I handle this?