You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Karma/Jasmine中监视带有重载签名的方法?

解决Angular单元测试中重载方法的Spy类型不兼容问题

你的问题出在TypeScript对重载方法的类型推断逻辑上:sendRequest的重载签名让TS默认优先匹配返回Observable的分支,而你模拟返回的是Promise,导致类型不匹配报错。下面是几种可行的解决方式:

方式一:明确指定重载分支的类型

在创建Spy时,通过参数匹配或类型断言,让TS识别你要模拟的是返回Promise的重载:

// 匹配第二个参数为false的调用,明确对应返回Promise的重载
const spySendRequest = spyOn(service["httpService"], "sendRequest")
  .withArgs(jasmine.any(String), false)
  .and.returnValue(Promise.resolve(resultExpected));

或者直接对返回值做类型断言,告诉TS返回的是Promise类型:

const spySendRequest = spyOn(service["httpService"], "sendRequest")
  .and.returnValue(Promise.resolve(resultExpected) as Promise<typeof resultExpected>);

方式二:用callFake根据参数动态返回

如果测试场景中sendRequest可能被传入不同的observable参数,可通过callFake根据参数返回对应类型:

import { of } from 'rxjs';

const spySendRequest = spyOn(service["httpService"], "sendRequest").and.callFake(
  (path: string, observable = false) => {
    return observable ? of(resultExpected) : Promise.resolve(resultExpected);
  }
);

方式三:临时用类型断言绕过检查(不推荐)

若以上方式都不适用,可通过as any强制绕过TS类型检查,但这会丢失类型校验的意义,仅作为临时方案:

const spySendRequest = spyOn(service["httpService"], "sendRequest")
  .and.returnValue(Promise.resolve(resultExpected) as any);

内容的提问来源于stack exchange,提问作者Haezer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:57:43