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

Angular Jasmine测试spyOnProperty报错:getRequestInfo未声明可配置

解决Angular测试中spyOnProperty报错:getRequestInfo is not declared configurable

问题根源

  1. 函数与属性混淆:getRequestInfo是一个独立导出的工具函数,并非MyConfig对象的属性。你在测试中试图给config手动添加该属性并通过spyOnProperty监听,但直接添加的对象属性默认configurable为false,触发报错。
  2. 测试代码调用错误:组件中目标方法是getRequestInfoDetails,但测试里调用的是component.getForm(config),方法名不匹配。
  3. 字段不匹配:组件判断的是config.update,但测试中给config定义的是status: 'true',会导致getRequestInfo不会被执行。

修复方案

要监听独立导出的函数,需使用spyOn而非spyOnProperty,并指定函数所在的模块:

// 导入getRequestInfo所在的模块
import * as MyConfigModule from './path-to/MyConfig';

it('getRequestInfoDetails 应调用 getRequestInfo', () => {
    const myFrmgrp = new FormGroup({}); 
    // 修正config字段,匹配组件判断逻辑
    const config: MyConfig = {
        update: 'true',
        // 补充MyConfig所需的其他字段
    };
    // 监听独立导出的函数
    const getRequestInfoSpy = spyOn(MyConfigModule, 'getRequestInfo').and.returnValue({});
    
    // 调用组件的正确方法
    component.getRequestInfoDetails(config);
    
    expect(getRequestInfoSpy).toHaveBeenCalled();
});

关键说明

  • spyOn用于监听模块导出的独立函数,spyOnProperty仅适用于对象的getter/setter访问器属性,二者不可混用。
  • 确保测试中config的字段与组件判断逻辑一致,否则无法触发目标函数调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:17:10