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

如何编写SpyOn()方法?附测试示例代码解析

如何编写SpyOn()方法及测试示例

SpyOn的作用

SpyOn 是测试框架(如Jasmine)中用于监听组件方法的工具,可实现拦截方法调用、预设返回值、验证方法调用情况等测试需求。

测试示例代码

let component = MockComponent;

it('验证组件方法被调用', () => {
  // 先为目标方法挂载Spy,预设返回值
  spyOn(component, 'method').and.returnValue('预期数据');

  // 调用组件方法
  component.yourComponent();

  // 可选:验证method方法是否被触发调用
  expect(component.method).toHaveBeenCalled();
});

代码说明

  • 先通过spyOn(component, 'method')监听组件的method方法,再用.and.returnValue('预期数据')预设该方法的返回值
  • 调用组件的yourComponent方法,若yourComponent内部调用了method,Spy会自动拦截并返回预设值
  • 可通过expect(component.method).toHaveBeenCalled()验证method是否被成功触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:27:02