0
votes

I'm writing my Jest tests in TypeScript and I'd like to create a strongly typed mock for a function like this:

function download(
  options: DownloadOptions,
  callback?: (downloadId: number) => void
): void;

Note that the callback is optional. If I use jest.Mock to cast the mocked function...

const mockDownload = jest.fn() as jest.Mock<void, [
  DownloadOptions,
  ((downloadId: number) => void)?
]>

... and try to use it like this:

download.mockImplementation(
  (
    options: DownloadOptions,
    callback: (downloadId: number) => void,
  ) => callback(0),
)

... I get TS Error 2345:

Argument of type '(options: DownloadOptions, callback: (downloadId: number) => void) => void' is not assignable to parameter of type '(options: DownloadOptions, callback?: ((downloadId: number) => void) | undefined) => void'.

Types of parameters 'callback' and 'callback' are incompatible.

Type '((downloadId: number) => void) | undefined' is not assignable to type '(downloadId: number) => void'.

Type 'undefined' is not assignable to type '(downloadId: number) => void'.

1

1 Answers

0
votes

Use jest.MockedFunction, remove the types from the mock implementation function and optionally call the callback.

const mockDownload = jest.fn() as jest.MockedFunction<typeof download>

mockDownload.mockImplementation((options, callback) => callback?.(0))