Angular 单元测试 - 如何窥探可观察的属性

标签 angular unit-testing karma-jasmine

我想为可观察属性设置发射值/下面是代码

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/

相关文章:

angular - 在 Angular 指令中包装 ngx-bootstrap/typeahead

unit-testing - 基于 JSP servlet 的 Web 应用程序的功能测试

java - junit 和 psvm 有什么区别

javascript - Jasmine spy 与兑现 promise

javascript - 找到合成属性@enterAnimation。请在您的申请中包含 "BrowserAnimationsModule"或 "NoopAnimationsModule"。 Angular 4

node.js - 从 TypeScript 初始化 Firebase Admin SDK 失败

Angular Material 垫波纹不起作用

java - 获取特定 JTable 单元格中的前景(字体)

angularjs - 使用 Jasmine 2 和 karma 测试 Angular $q

javascript - 第一个 url 参数与所有 url 地址混淆