如何使用提供的angular代码创建测试用例



我是angular的新手,在测试方面有一些问题。以下是homecomponent.ts:上的部分代码

ngOnInit(): void {
this.mapService.mapLoaded$.subscribe(
state => {
this.loadingState = state;
}
);
if (!this.isMobile || this.selectedView === 'map') {
this.mapService.canLoadMap$.next(true);
} else { this.mapService.triggerMapLoadedTransition(); }
this.filterService.canLoadFilter$.next(true);
}
I am trying to test the map service and filter service but couldn't make it work. here's the code so far:
it('should trigger canLoadFilter to equal to true', () => {
let fixture = TestBed.createComponent(HomeComponent);
let app = fixture.debugElement.componentInstance;
component.selectedView = 'test';
fixture.detectChanges();
expect(partialFilterService.canLoadFilter$.next).toEqual(true);
});
I'm not sure with mapservice yet but any suggestions will be highly appreciated.

您不能期望下一个函数返回true。要检查canLoadFilter$是否在observable中推送true。您应该订阅canLoadFilter$来检查它是否返回真实值

describe('on init', () => {
fit(`should push a true value in the observable`, async(() => { // use waitForAsync in lastest angular versions
const filterService = TestBed.inject(FilterService); // use TestBed.get in previous angular versions 
filterService.canLoadFilter$.subscribe((val) => {
expect(val).toEqual('true');
})
fixture.detectChanges();
}));
});

最新更新