You need to enable JavaScript to run this app. Angular11单元测试为NgForm创建spy时报找不到可监听对象的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Angular11单元测试为NgForm创建spy时报找不到可监听对象的问题咨询

开发场景:Angular 11 组件单元测试NgForm对象spy创建失败

测试环境与组件初始化代码

let component: AuthComponent;
let fixture: ComponentFixture<AuthComponent>;

beforeEach(() => {
  TestBed.resetTestEnvironment();
  TestBed.initTestEnvironment(BrowserDynamicTestingModule, 
    platformBrowserDynamicTesting());
  // 省略其余测试模块引入逻辑
  fixture = TestBed.createComponent(AuthComponent);
  // 省略组件实例绑定逻辑
}

onSubmit方法测试用例实现

describe('onSubmit', () => {
  it('makes expected calls', () => {
    const ngFormStub: NgForm = <NgForm>{};
    spyOn(ngFormStub, 'resetForm').and.callThrough();
    component.onSubmit(ngFormStub);
    expect(ngFormStub.resetForm).toHaveBeenCalled();
  });
});

遇到的问题与疑问

  • 待验证的核心逻辑:组件内onSubmit方法执行到末尾会调用传入表单的resetForm(),该调用是测试需要覆盖验证的核心点。
  • 已尝试的无效操作:曾尝试直接从组件实例上获取表单对象作为测试桩,写法为const ngFormStub: NgForm = component.form;,但该方式没有正常返回可用的NgForm实例。
  • 测试运行报错:按照空对象强转的方式写测试桩时,控制台抛出如下Jasmine报错:
    Error: <spyOn> : could not find an object to spy upon for resetForm()
    
  • 核心疑问:是否必须通过fixture获取真实的NgForm实例作为测试桩,才能正常创建spy?

当前项目测试相关依赖版本

"jasmine": "^3.6.3",
"jasmine-core": "^3.6.0",
"jasmine-spec-reporter": "^6.0.0",
"karma": "^5.2.3",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "^4.0.1",
"karma-jasmine-html-reporter": "^1.5.4"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.16 03:45:04