Skip to main content

How to mock calls in jest

· One min read
Hreniuc Cristian-Alexandru

When you want to test a function that uses a method from an object, you can mock the method and check if it was called with the right parameters. For example, this is how to mock for sendNotification method from firebaseService object:

import { firebaseService } from '../../../firebase/firebase';

let mockSendNotification: jest.Mock;

describe('Tests suit', () => {

test('Test1', async () => {
mockSendNotification = jest.fn();
firebaseService.sendNotification = mockSendNotification;

// call the function that uses firebaseService.sendNotification

expect(mockSendNotification).toHaveBeenCalledWith(
C1.notifications.N1U4S1.contents,
C1.notifications.N1U4S1.subscriptions,
);
});
});

And if you want to check if the method was called multiple times with different parameters, you can use toHaveBeenNthCalledWith:

expect(mockSendNotification).toHaveBeenNthCalledWith(
1,
C1.notifications.N4U1S2E1.contents,
C1.notifications.N4U1S2E1.subscriptions,
);
expect(mockSendNotification).toHaveBeenNthCalledWith(
2,
C1.notifications.N5U1S2E2.contents,
C1.notifications.N5U1S2E2.subscriptions,
);