'Jest SpyOn choose the correct overload
I do have a class that has 2 overloaded methods.
public static create<M extends Model>(
this: ModelStatic<M>,
values?: M['_creationAttributes'],
options?: CreateOptions<M['_attributes']>
): Promise<M>;
public static create<M extends Model>(
this: ModelStatic<M>,
values: M['_creationAttributes'],
options: CreateOptions<M['_attributes']> & { returning: false }
): Promise<void>;
in my unit test, I'm trying to use jest.spyOn
to mock the first method however jest sees only the one that returns Promise<void>
.
const mockInsightCreate = jest.spyOn(Insight, "create");
mockInsightCreate.mockReturnValue(Promise.resolve()); // here I need to return an object of type - Insight
Is there a way to instruct spyOn
to pickup the first method that returns Promise<M>
?
import {
Model,
} from "sequelize-typescript";
...
export default class Insight extends Model<Insight> {
Solution 1:[1]
I know this question is old, but bellow is my answer for anyone facing the same issue who might stumble across it.
There is currently no way of instructing which overload signature spyOn
should use. One solution would be to cast the value to whatever spyOn
expects.
mySpy.mockReturnValue(Promise.resolve(myObj) as unknown as void);
mySpy.mockResolveValue(myObj as unknown as void);
However, I personally prefer avoiding coercing the typing system if possible. Another workaround that does not require any typing judo is to mock the entire method implementation.
mySpy.mockImplementation(() => Promise.resolve(myObj));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Antoine Viscardi |