如何在karma中模拟这个服务变量



我有这样一个场景

组成部分

constructor( private serviceA: ServiceA, private serviceB: ServiceB) {
this.anotherVariable = this.serviceA.config.ABC
}

规范部分
const ServiceAStub = {
config: {
ABC: '1',
},
};
describe('Component', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let appconfigService: AppConfigService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Component],
providers: [
{ provide: SerciveA, useValue: ServiceAStub },
{ provide: SerciveB, useValue: {}},
],
}).compileComponents();    
}));
beforeEach(() => {    
fixture = TestBed.createComponent(Component);
component = fixture.componentInstance;    
fixture.detectChanges();
});
it('should create the component', () => {
expect(component).toBeTruthy();
});

运行此规范返回错误

TypeError: Cannot read properties of undefined (reading 'ABC')

我怎样才能嘲笑它,让它通过呢?

尝试以下版本:

spec file -

const ServiceAStub = {
config: {
ABC: '1',
},
};
describe('Component', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let appconfigService: AppConfigService;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [Component],
providers: [
{ provide: ServiceA, useValue: ServiceAStub },
{ provide: ServiceB, useValue: {}},
],
});
fixture = TestBed.createComponent(Component);
component = fixture.componentInstance;    
fixture.detectChanges();
});
it('should create the component', () => {
expect(component).toBeTruthy();
});

comp file -

constructor( private serviceA: ServiceA, private serviceB: ServiceB) {}

public ngOnInit(): void {
this.anotherVariable = this.serviceA.config.ABC;
}

如果你仍然遇到问题,那么请把你的工作代码放在stack blitz上并共享。

最新更新