Skip to content

Instantly share code, notes, and snippets.

@vesse
Last active April 9, 2024 10:49
Show Gist options
  • Save vesse/f1b1f6d2af39daa3381a0a09f940a4b2 to your computer and use it in GitHub Desktop.
Save vesse/f1b1f6d2af39daa3381a0a09f940a4b2 to your computer and use it in GitHub Desktop.
Mock 3rd party class with Jest in Typescript
import routeHandler from '../src/routeHandler';
import { mockResponse, mockRequest } from './test-helpers';
jest.mock('@googlemaps/google-maps-services-js');
import { Client } from '@googlemaps/google-maps-services-js';
const mockClient = {
geocode: jest.fn(),
};
(Client as jest.Mock).mockImplementation(() => mockClient);
describe('routeHandler', () => {
it('should call Google geocoder and return', async () => {
const req = mockRequest();
const res = mockResponse();
mockClient.geocode.mockResolvedValue('kissa');
await routeHandler(req, res, jest.fn());
expect(res.send).toHaveBeenCalledWith({ result: 'kissa' });
});
});
import type { Response, Request } from 'express';
export const mockResponse = (opts?: Partial<Response>): Response =>
(({
send: jest.fn(),
json: jest.fn(),
status: jest.fn(),
...opts,
} as unknown) as Response);
export const mockRequest = (opts?: Partial<Request>): Request =>
(({
body: {},
...opts,
} as unknown) as Request);
@tugzera
Copy link

tugzera commented Jun 11, 2021

U saved my life bro!! THX :D

@heyralfs
Copy link

Nice! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment