gpt4 book ai didi

angular - 在 Angular 6 组件 ngOnInit 函数中测试 rxjs 间隔

转载 作者:行者123 更新时间:2023-12-04 01:51:48 24 4
gpt4 key购买 nike

我有一个具有以下 ngOnInit 函数的组件,它轮询服务方法以获取状态更新:

ngOnInit() {
interval(2000).pipe(
switchMap(() => this.dataService.getStatus())
).subscribe((result) => {
this.uploadStatus = result;
);
}

我正在尝试使用以下代码测试更新是否实际发生:

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


it('should start checking for status updates', fakeAsync(() => {
const dataService = TestBed.get(DataService);
// Mock the getStatus function
spyOn(dataService, 'getStatus').and.returnValue(Observable.create().pipe(map(() => 'woo')));
// Should not be initialised yet
expect(component.uploadStatus).toBeUndefined();
tick(2000);
expect(component.uploadStatus).toBe('woo');
}));

但是 component.uploadStatus 始终为空。我应该如何去测试这种类型的场景?理想情况下,我想随着时间的推移检查多个更新。

谢谢

最佳答案

我最终确定的是以下内容。我还必须存储订阅,以便我可以在测试结束时取消它,以防止“周期性计时器仍在队列中”错误:

ngOnInit() {
// Store the subscription so we can unsubscribe when testing
this.pollingSubscription = interval(2000).pipe(
switchMap(() => this.dataService.getStatus())
).subscribe((result) => {
this.uploadStatus = result;
});
}

然后进行如下测试:

it(`init`, fakeAsync(inject([DataService],
(dataService: DataService) => {
const testReturns = [
of('woo'),
of('yay')
];
let currentReturn = -1;
spyOn(dataService, 'getStatus').and.callFake(() => {
currentReturn++;
return testReturns[currentReturn];
});

expect(component.uploadStatus).toBeUndefined();
fixture.detectChanges();
// expect(component.uploadStatus).toBe('Login');
// spyOn(dataService, 'getStatus').and.returnValue(of('woo'));
component.ngOnInit();
tick(2000);
expect(component.uploadStatus).toBe('woo');
tick(2000);
expect(component.uploadStatus).toBe('yay');

// Unsubscribe to prevent the "periodic timers still in queue" errors
component.pollingSubscription.unsubscribe();
})));

关于angular - 在 Angular 6 组件 ngOnInit 函数中测试 rxjs 间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52629026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com