I have a function in a module segmentEvents.ts and I want to assert that another function is called when I call the first. The problem is that I am unable to mock the second function to check it’s called. No matter what I do the real implementation of the function is called.
What am I doing wrong here? How do I mock trackEvent?
Here is my code, all files in the same directory
test.spec.ts
jest.mock('./segment', () => ({
trackEvent: jest.fn(),
}));
import { expect } from '@jest/globals';
import eventHandlers from './segmentEvents';
import { trackEvent } from './segment';
describe('Segment Events', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should call trackEvent when someEvent is invoked', () => {
console.log('trackEvent', trackEvent); // is supposed to be a mock function but it's not
eventHandlers.someEvent();
expect(trackEvent).toHaveBeenCalled();
});
});
segmentEvents.ts
import { trackEvent } from "./segment";
function mealPlanSelected(): void {
trackEvent();
}
const eventHandlers = {
mealPlanSelected,
};
export default eventHandlers;
src/utils/segment.ts
export const trackEvent = (): String => {
console.log("***Event Tracked***");
return 'test';
}
1