Skip to content

[Bug]: (types) spyOn has trouble selecting the correct overload for some methods #15998

@dmurvihill

Description

@dmurvihill

Version

29.5.0

Steps to reproduce

This is a bug, or maybe unavoidable limitation, in the @types/jest package from DefinitelyTyped rather than Jest itself. I'm filing here in case it's of interest to the Jest core team and so it can be found by users who may not be aware of DefinitelyTyped.

Here we have a function that's overloaded with a sync/callback implementation and a Promise version. The return type is either void or Promise depending on whether the user passes a callback:

function callbackable(): Promise<void>;
function callbackable(cb: (err?: void) => void): void;
function callbackable(cb?: (err?: void) => void) {
    if (!cb) {
        return Promise.resolve();
    }
}

const o = {
    callbackable,
}

jest.spyOn(o, 'callbackable').mockRejectedValueOnce(new Error('test')); // TS2345: Argument of type Error is not assignable to parameter of type never

When referencing with spyOn, the type system gets its return type form the first overload rather than accepting any that will fit.

See also: DefinitelyTyped #74690.

Expected behavior

Good type check

Actual behavior

TS2345: Argument of type Error is not assignable to parameter of type never

Additional context

No response

Environment

TS 5.9.3
Jest 29

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions