[英]How to unit test Rxjs combineLatest?
我的組件的 ngOnInit 執行此操作
public ngOnInit() {
this.ctrSubscription = combineLatest(this.route.queryParams, this.tags$).subscribe(async params => {
if (Object.keys(params[0]).length > 0) {
this.initView({ ...params[0] });
}
if (Object.keys(params[1]).length > 0) {
this.wsTags = Object.values(params[1]);
}
if (params[0] && this.wsTags.length > 0) {
this.searchWs({ ...params[0] }.q);
this.pruneData();
}
});
}
這就是我測試它的方式
it('should perform search and load the results', fakeAsync(() => {
TestBed.get(ActivatedRoute).queryParams = of({ q: 'test' });
const initSpy = spyOn<any>(component, 'initView').and.callThrough();
const subSpy = spyOn<any>(component.tags$, 'subscribe');
component.wsTags = ensureState(mockTags as any);
flushMicroTasks();
fixture.detectChanges();
flushMicroTasks();
expect(initSpy).toHaveBeenCalledWith({ q: 'test' });
expect(subSpy).toHaveBeenCalled();
expect(component.wsTags).toBe(Object.values(mockTags));
}));
間諜根本沒有被調用。我在運行測試時設置了一個斷點以了解值是否通過,並且我能夠捕獲正確傳遞的查詢參數,但 if 仍然失敗。
我嘗試瀏覽文檔以更好地理解堆棧溢出以及這里的各種類似問題,但我無法解決它。 我對編寫單元測試相當陌生,因此將不勝感激。 謝謝。
一個潛在的問題是您在it
塊中模擬了ActivatedRoute
。 這太晚了,您的ngOnInit
在ngOnInit
之后的第一個detectChanges
之后compileComponents
。
配置測試模塊時,請嘗試:
describe('Put description of the test', () => {
let component: YourComponent;
let activatedRoute: ActivatedRoute;
let fixture: ComponentFixture<YourComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ YourComponentToTest,
// other declarations if need be.
],
providers: [
provide: ActivatedRoute,
useValue: {
queryParams: of({ q: 'test" }),
}
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(YourComponentToTest);
component = fixture.componentInstance;
activatedRoute = TestBed.get(ActivatedRoute);
// ngOnInit is ran now -- after the first detectChanges
fixture.detectChanges();
});
it('should do what you want', () => {
// your arrange, act, and assertions.
});
})
確保this.tags$
已初始化。
所有這些都是徒手完成的,所以可能會有錯字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.