Three lines of Typescript with jest to get typesafe mocks

austinbv

Austin Vance

Posted on January 14, 2020

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
💖 💪 🙅 🚩
austinbv
Austin Vance

Posted on January 14, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related