TypeScript: typing a mocked module function with a different signature in Jest

1 week ago 15
ARTICLE AD BOX

I want to mock a specific module with a specific mocked function.
Later on, I want to supply the implementation in a specific test.

I have this code:

import fs from "fs"; jest.mock("fs", () => ({ readFileSync: jest.fn() })); const mockedFs = jest.mocked("fs"); test("my test", () => { mockedFs.readFileSync.mockImplementation((s: string) => s); };

But TypeScript complains:

Argument of type '(s: string) => string' is not assignable to parameter of type '(path: PathOrFileDescriptor, options?: (ObjectEncodingOptions & { flag?: string | undefined; }) | BufferEncoding | null | undefined) => string | NonSharedBuffer'. Types of parameters 's' and 'path' are incompatible. Type 'PathOrFileDescriptor' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.

I can also get rid of the type like this: const mockedFs = jest.mocked(fs) as any but I prefer to find the correct usage.

The intention is to simplify the implementation of a mock function that is always going to be called with an argument of the same type, but can accept multiple types in the original function definition.

Read Entire Article