我想为可观察属性设置发射值/下面是代码
export class PostListComponent implements OnInit {
errorMessage = '';
loggedInUser: User | undefined;
cachedPost: Post | undefined;
private selectedTabSubject = new BehaviorSubject<number>(0);
selectedTabAction$ = this.selectedTabSubject.asObservable();
selectedTabAction$ 是订阅控件操作的属性,即下拉列表更改并返回所选值。
我如何模拟/spyon 这个属性,以便我可以在单元测试中控制我想要的值。
最佳答案
在您的单元测试中,在您要模拟的属性上创建一个 spy 。
...
fixture = TestBed.createComponent(PostListComponent);
component = fixture.componentInstance;
const theValueYouWantToEmit = 3;
spyOnProperty(component, 'selectedTabAction$', 'get').and.returnValue(of(theValueYouWantToEmit));
更新:因为它是一个字段而不是一个属性,所以您可以做的一件事就是围绕该字段创建一个属性,就像这样。
export class PostListComponent implements OnInit {
private _selectedTabSubject = new BehaviorSubject<number>(0);
get selectedTabSubject(): BehaviorSubject<number> {
return this._selectedTabSubject;
}
set selectedTabSubject(value: BehaviorSubject<number>) {
this._selectedTabSubject = value;
}
selectedTabAction$ = this._selectedTabSubject.asObservable();
关于 Angular 单元测试 - 如何窥探可观察的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68977138/