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

Angular 16跨文件函数调用的Jasmine Spy测试问题及解决

Angular 16中Jasmine spyOn独立函数报错的解决方法

问题场景

在Angular 16项目中,有两个分属不同.ts文件的独立函数:functionUnderTest与functionToTest,二者均返回Observable类型。为验证调用functionUnderTest时是否触发functionToTest,编写了如下Jasmine测试代码:

import { functionUnderTest} from './File1';
import * as File2 from './File2';

describe("Test Suite", () => {
  it("test Function with spy", () => {

    spyOn(File2, 'functionToTest').and.callThrough();

    functionUnderTest('test parameter').subscribe(() => {

      expect(File2.functionToTest).toHaveBeenCalled();
      expect(File2.functionToTest).toHaveBeenCalledWith('test parameter');

    });
  });
}); 

报错信息

执行测试时抛出如下错误:

Error: <spyOn> : functionToTest is not declared writable or has no setter
Usage: spyOn(<object>, <methodName>)

解决方法

在项目的tsconfig.spec.json文件中,修改compilerOptions配置,添加"module": "commonjs"即可解决该问题:

{
  "compilerOptions": {
    // 保留原有配置
    "module": "commonjs"
  },
  // 其他配置项
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:27:06