我目前正在测试我创建的一个简单组件,它看起来像这样:
@Input()
public type: string;
private saveSubscription: Subscription;
public ngOnDestroy(): void {
this.saveSubscription.unsubscribe();
}
public ngOnInit(): void {
this.onSave();
}
private onSave(): void {
this.saveSubscription = this.editService.saveSelection.subscribe(() => {
this.editService.type.next(this.type);
});
}
在我的测试中,我想确保如果我手动设置输入,然后调用 ngOnInit()
,editService
发出的值将等于我的值(value)。
it('should set up the subscription for saving', fakeAsync(() => {
// Arrange
component.type = 'full';
// Act
component.ngOnInit();
fixture.detectChanges();
mockedEditService.saveSelection.next();
// Assert
mockedEditService.type.subscribe(type => {
expect(type).toEqual(component.type);
});
}));
我正在为测试异步代码而苦苦挣扎,并且不确定我是否正确地执行了此操作。即使测试用例不正确,测试也总是通过,我怀疑有问题的代码在做出断言之前没有等待订阅解决。
阅读 Angular test docs ,我已经能够更加熟悉自己了,但我想知道你们是否有任何建议。
谢谢
最佳答案
在 spec
中,在 mockedEditService.saveSelection.next
之前有 subscription
it('should set up the subscription for saving', fakeAsync(() => {
// Arrange
component.type = 'full';
// START ********* MOVE THIS BLOCK UP
mockedEditService.type.subscribe(type => {
expect(type).toEqual(component.type);
});
// END ********* MOVE THIS BLOCK UP
// Act
component.ngOnInit();
fixture.detectChanges();
mockedEditService.saveSelection.next();
}));
关于angular - 正确测试简单组件的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137941/