Back
Blog

Three lines of Typescript with Jest to Get Typesafe Mocks

Jan 14, 2020

By Austin Vance

Share:
  • linkedin
  • facebook
  • instagram
  • twitter

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
  });
});
Back to Explore Focused Lab
/Contact us

Let’s build better software together