在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
相关产品推荐
相关产品推荐

