Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 780
Ka Mok Avatar asked Feb 28 '18 16:02

Ka Mok


People also ask

What is SpyOn in angular unit testing?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.


1 Answers

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

spyOnProperty(userService.user, 'value', 'get').and.returnValue({ 'username': 'username'});
like image 168
Sujith Avatar answered Oct 10 '22 02:10

Sujith