angular unit test - How to spyon observable property

Viewed 1570

I want to set emit value for observable property/ the below is the code

export class PostListComponent implements OnInit {
  errorMessage = '';
  loggedInUser: User | undefined;
  cachedPost: Post | undefined;
  private selectedTabSubject = new BehaviorSubject<number>(0);
  selectedTabAction$ = this.selectedTabSubject.asObservable();

selectedTabAction$ is the property which subscribe to the control action i.e on dropdown list changes and returns selected value.

how can i mock /spyon this property so that i can control what value i want in a unit test.

1 Answers

In your unit test, create a spy on the property you want to mock.

...
fixture = TestBed.createComponent(PostListComponent);
component = fixture.componentInstance;

const theValueYouWantToEmit = 3;
spyOnProperty(component, 'selectedTabAction$', 'get').and.returnValue(of(theValueYouWantToEmit));

Update: Since it's a field and not a property, one thing you could do is to create a property around that field, like so.

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();
Related