I am new user trying to learn jest in a Typescript environment via ts-jest. One of the functions that I wish to 'spyOn' uses generics. Is it possible to spy on a generic function and mock a typed return value?
For example:
export class Api {
private api: AxiosInstance;
constructor(api: AxiosInstance = axios) {
this.api = api;
}
public all<T, From = T, TF extends ITransform<From, T> = never>(
url: string,
transformer?: TF,
): Observable<AxiosResponse<T[]>> {
return this.requestAll<T, From, TF>(url, transformer);
}
I have tried with:
const allSpy = jest.spyOn<Api, 'all'>(Api.prototype, 'all');
In this case allSpy has the following type information:
const allSpy: jest.SpyInstance<Observable<AxiosResponse<unknown[]>>, [string, (ITransform<any, any> | undefined)?]>
I receive a type compilation error if I try to mock a return value:
const response: AxiosResponse<MyObj[]> = {
data: [
{ id: 1014760, objName: 'Object 1' },
{ id: 1015762, objName: 'Object 2' },
],
status: 200,
statusText: 'ok',
headers: {},
config: {},
};
allSpy.mockReturnValueOnce(response); // type error for response
尝试存根而不是间谍,你将能够得到它。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.