Skip to content

Blog

Three lines of Typescript with jest to get typesafe mocks

01.14.2020 | Testing Frontend | Austin Vance
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();

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> {
    // #...
  }
}
export class Map {
  constructor(locationService: LocationService) {
    this.locationService = locationService
  }

  setPosition(): Position {
    const position = this.locationService.getCurrentPosition
    // # ...
    // # Do something with position
  }
}
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
  });
});

Share