Answer the question
In order to leave comments, you need to log in
How to fix "No overload matches this call" error in jest.spyOn on a private method?
private getPosOnScale(currentPos: number): number {
const sliderRect = this.slider.element!.getBoundingClientRect();
return this.settings.isVertical
? currentPos - sliderRect.top
: currentPos - sliderRect.left;
}
describe('some method', () => {
test('should return smth', () => {
const view = new View('range-slider', settings);
jest.spyOn(view, 'getPosOnScale').mockReturnValue(100);
// code
});
});
No overload matches this call.
Overload 1 of 4, '(object: View, method: FunctionPropertyNames>): SpyInstance', gave the following error.
Argument of type '"getPosOnScale"' is not assignable to parameter of type 'FunctionPropertyNames>'.
Overload 2 of 4, '(object: View, method: never): SpyInstance', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'never'.ts(2769)
Answer the question
In order to leave comments, you need to log in
jest.spyOn has 4 overloads that separate ordinary fields (these overloads have a 3rd parameter 'get' | 'set'
), methods (functional type on the instance) and static methods (functional type on the class itself).
Your call implies just a method.
The problem is that private and protected fields don't match as function types. Private fields have no type at all outside the class, while protected fields have a type only in the descendant.
It remains only to cheat the type system:
declare class ViewHack {
getPosOnScale(currentPos: number): number;
}
describe('some method', () => {
test('should return smth', () => {
const view = new View('range-slider', settings);
jest.spyOn(view as unknown as ViewHack, 'getPosOnScale').mockReturnValue(100);
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question