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
相关产品推荐
相关产品推荐

