Skip to content

Instantly share code, notes, and snippets.

@vesse
Last active November 21, 2024 16:27
Show Gist options
  • Select an option

  • Save vesse/f1b1f6d2af39daa3381a0a09f940a4b2 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

tugzera commented Jun 11, 2021

U saved my life bro!! THX :D

@heyralfs
Copy link
Copy Markdown

Nice! Thank you!

@martinmcwhorter
Copy link
Copy Markdown

Life saver. The scales have fallen from mine eyes.

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