DEV Community

Cover image for Three lines of Typescript with jest to get typesafe mocks
Austin Vance for Focused

Posted on • Updated on • Originally published at focusedlabs.io

Three lines of Typescript with jest to get typesafe mocks

First the three important lines for anyone who needs to copypaste. I'll explain later!

jest.mock('@/components/LocationService');
const MockedLocationService = <jest.Mock<LocationService>>LocationService;
const mockedLocationService = <jest.Mocked<LocationService>> new MockedLocationService();

Enter fullscreen mode Exit fullscreen mode

Now a bit of explanation. When you use jest to mock an import (which I am still not convinced is a good pattern) the mock is still typed as the original import. This means that Typescript will complain if you do something like MockedImport.mocks.

Below is an example setup where this would be useful

If you need to mock implementation

export class LocationService {
  async getCurrentLocation(): Promise<CurrentPosition> {
    // #...
  }
}
Enter fullscreen mode Exit fullscreen mode
export class Map {
  constructor(locationService: LocationService) {
    this.locationService = locationService
  }

  setPosition(): Position {
    const position = this.locationService.getCurrentPosition
    // # ...
    // # Do something with position
  }
}
Enter fullscreen mode Exit fullscreen mode
jest.mock('@/components/LocationService');

describe('Map.ts', () => {
  it('uses the current location to set the position', () => {
    const MockedLocationService = <jest.Mock<LocationService>>LocationService;
    const mockedLocationService = <jest.Mocked<LocationService>>new MockedLocationService();
    mockedLocationService.getCurrentLocation.mockResolvedValue({ lat: 3, long: 3 });

    const map = new Map(mockedLocationService)

    // # Do something with your mocked instance
  });
});
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
anilanar profile image
Anıl Anar

More concise solution: github.com/userlike/joke