我是新用户,试图通过 ts-jest 在 Typescript 环境中学习 jest。我希望“spyOn”的功能之一使用泛型。是否可以监视通用函数并模拟类型化的返回值?
例如:
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);
}
我尝试过:
const allSpy = jest.spyOn<Api, 'all'>(Api.prototype, 'all');
在这种情况下allSpy具有以下类型信息:
const allSpy: jest.SpyInstance<Observable<AxiosResponse<unknown[]>>, [string, (ITransform<any, any> | undefined)?]>
如果我尝试模拟返回值,则会收到类型编译错误:
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