Mocking Single Exported Functions with TypeScript and Jest
Mocking functions is really easy to do in Jest but what if the module is exporting a functions directly instead of bundling them in a class? Well, it is actually quite easy to do if you know this simple trick.
Take this TypeScript class (the whole procedure also works in pure JavaScript):
export class UserDBClient {
getName(userId: number): string {
// some magic
return userId
}
}
You might mock the method getName
within your unit tests like this:
import UserDBClient from 'src/user-db-client'
jest.spyOn(UserDBClient.prototype, 'getName').mockResolvedValue('Homer Simpson')
// some unit tests
But what if the module exports single functions instead of a class containing the methods? Take this example:
export function getName(userId: number): string {
// some magic
return userId
}
Well, you can leverage a very simple trick to still use jest.spyOn
. You just need to import the entire module into one variable within your test file and use it as if it was a class:
import * as UserDBClient from 'src/user-db-client'
jest.spyOn(UserDBClient.prototype, 'getName').mockResolvedValue('Homer Simpson')
// some unit tests
This is a very small example but over the past years I have seen multiple projects from different companies where the presence of exported functions had caused troubles when writing tests because developers struggled to mock them correctly.
When I was asked for help regarding unit tests in Jest, around 75% of the time this (in slight variations) was the solution to their problem.