Three lines of Typescript with jest to get typesafe mocks

01.14.2020 | Testing Frontend | Austin Vance


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

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

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


Read More

Related Posts


06.30.2021 | Culture | Katy Scott

At Focused Labs, collaboration is key to how we work together; it helps our teams learn from each other, brings us closer and helps us become more efficient...


06.23.2021 | Culture | Austyn

Late-night feedings and diaper changes, the 3-4 month sleep regression, teething, and a growth spurt all mean I'm getting less sleep than...


05.12.2021 | Culture Backend Frontend | Ryan Taylor

Temporarily disrupts "normal" business operations and allow self-organized teams to rapid prototype around their interest areas


04.27.2021 | Culture | Erin Hochstatter

Several years ago, I'd been trying to find an approach to software consulting that made sense for me [...]


01.28.2021 | Backend | Parker Drake

Recently I found myself needing to validate fields in a Spring Boot controller written in Kotlin...


01.22.2021 | Tutorial | Luke Mueller

⌘+⇧+g is the way to go


01.21.2021 | Devops | Katy G

Kube jobs running wild? To delete successful jobs...

additional accent

171 N Aberdeen St
Suite 400
Chicago, IL 60607
(708) 303-8088

[email protected]

© 2021 FocusedLabs, All Rights Reserved.

  • facebook icon
  • twitter icon
  • linkedin icon
  • github icon