Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking throws type error because it's using the wrong overload

Given the following in a Jest test:

const mockDirListing: string[] = ['sdafd', 'sfdf'];
const mockReaddirSync = jest.spyOn(fs, 'readdirSync');
mockReaddirSync.mockReturnValue(mockDirListing);

TypeScript will present the following error:

Argument of type 'string[]' is not assignable to parameter of type 'Dirent[]'.
Type 'string' is not assignable to type 'Dirent'.ts(2345)

The mocked instance has the type:

jest.SpyInstance<fs.Dirent[], [fs.PathLike, {
    encoding?: string;
    withFileTypes: true;
}]>

But the overload I would like to use in the SpyInstance is;

jest.SpyInstance<string[], [fs.PathLike, {
    encoding?: string;
    withFileTypes: true;
}]>

Anyone come across this before?

The same can be said about any classes with overloads, for example:

class Testing {
        foo(a: string): string;
        foo(a: number): string;
        foo(a: number | string): string {
            if (typeof a === 'string') return a;
            else if (a) return arguments.toString();
        }
    }

    test('testing', () => {
        const testing = new Testing();
        const mocked = jest.spyOn(testing, 'foo');
        mocked.mockImplementation((a: string) => a.toString());
    });

throws:

Argument of type '(a: string) => string' is not assignable to parameter of type '(a: number) => string'.
  Types of parameters 'a' and 'a' are incompatible.
    Type 'number' is not assignable to type 'string'.ts(2345)

How can I use the type signature of the first overload?

like image 409
Snewedon Avatar asked Nov 25 '25 10:11

Snewedon


1 Answers

We'll after looking into it, seems like the best you can really do is something like

const stub = (sinon.stub(fs, 'readdir') as unknown) as sinon.SinonStub<any[], Promise<Dirent[]>>;

Coercing the type to the once you specify.

like image 194
Snewedon Avatar answered Nov 26 '25 23:11

Snewedon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!