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

在Karma中如何正确mock服务变量解决config.ABC属性读取报错问题

问题根源

你遇到的报错是测试用例中注入令牌拼写错误导致的:
组件构造函数依赖的服务名为ServiceA、ServiceB,但在TestBed的providers配置中,你错误的把服务名拼写成了SerciveA、SerciveB,两者不匹配导致TestBed没有正确注入你定义的Stub,组件拿到的serviceA实际为undefined,访问undefined.config.ABC就触发了对应的类型错误。

修复方案

只要修正providers配置中的服务拼写即可,修改后的测试用例参考如下:

const ServiceAStub = {
    config: {
        ABC: '1',
    },
};

describe('Component', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;
    let appconfigService: AppConfigService;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [Component],
            providers: [
                // 修正拼写:从SerciveA改为ServiceA
                { provide: ServiceA, useValue: ServiceAStub },
                // 修正拼写:从SerciveB改为ServiceB
                { provide: ServiceB, useValue: {}},
            ],
        }).compileComponents();    
    }));

    beforeEach(() => {    
        fixture = TestBed.createComponent(Component);
        component = fixture.componentInstance;    
        fixture.detectChanges();
    });

    it('should create the component', () => {
        expect(component).toBeTruthy();
    });
});

可选优化建议

如果后续组件逻辑中会调用serviceB的属性或方法,建议提前给ServiceB的mock补全对应的属性结构,避免后续出现同类undefined报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:09:03