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

Angular单元测试SpyOn报错:期望调用setAccounttype未触发,求排查

问题原因分析

这是方法名大小写不匹配导致的错误,具体存在两处拼写不一致:

  1. 组件代码中调用的服务方法是SetAccountType(首字母为大写S),但测试代码里spyOn监听的是setAccountType(首字母为小写s)
  2. 断言部分的expect语句里写成了setAccounttype(末尾的T被写成小写t)

JavaScript/TypeScript是大小写敏感的语言,这两处拼写差异导致测试无法正确识别实际被调用的方法,因此抛出了"Expected spy 'setAccounttype' to have been called."的错误。

修正后的测试代码

it('should call the method', () => {
  spyOn(accountTypeService, 'SetAccountType'); // 与组件中调用的方法名大小写完全一致
  component.ngOnInit();
  expect(accountTypeService.SetAccountType).toHaveBeenCalled(); // 保持方法名拼写一致
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 05:52:06