Last active
November 21, 2024 16:27
-
-
Save vesse/f1b1f6d2af39daa3381a0a09f940a4b2 to your computer and use it in GitHub Desktop.
Mock 3rd party class with Jest in Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' }); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Nice! Thank you!
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
U saved my life bro!! THX :D