How to spyOn property of a Service that is a BehaviorSubject/Observable?

11,679

You can use spyOnProperty to return user object's mock.

spyOnProperty(userService.user, 'value', 'get').and.returnValue({ 'username': 'username'});
Share:
11,679

Related videos on Youtube

Ka Mok
Author by

Ka Mok

A pupil from whom nothing is ever demanded which he cannot do, never does all he can.

Updated on June 04, 2022

Comments

  • Ka Mok
    Ka Mok almost 2 years

    First of, spyOnProperty is giving me Property user does not have access type get with this line: spyOnProperty(userService, 'user', 'get').and.returnValue(Observable.of(adminUser));

    I have a UserService with a user property as such:

    export class UserService {
      user: BehaviorSubject<User> = new BehaviorSubject(new User());
    }
    

    The component that I'm testing needs to change behavior depending on the result of userService.user.subscribe. Hence, I need to be able to spy on user.

    One idea that I had was to write a method getter, eg getUser() on class UserService, and don't access user via a property.

    But that seems to be a bit extreme.

    Any ideas?

    • Boris Lobanov
      Boris Lobanov about 6 years
      BehaviorSubject has a getValue() method, not get