Apex
Apex

Reputation: 227

How to call a service with SpyOn function when doing Angular Unit Test

I have a service which returns a user object. The service uses a public property which sets from a private one.

private privateProperty: BehaviorSubject<User | Me | null> = new BehaviorSubject(
    null
  );

public publicProperty: Observable<
    User | Me | null
  > = this.privateProperty.asObservable();

The service request is invoked via a private method inside my component and I am having difficulty covering it in my unit test. I'm not sure how to set my test up to hit that private method and thus call the service and set some value to defined.

This is my test.

it('should set user oninit', ()=> {
    let me: Me | User;

    spyOn(userService, 'publicProperty').and.returnValue(of(userMock));

    component.ngOnInit();

    expect(userService.publicProperty).toHaveBeenCalled();
    expect(component.me).toBeDefined();

  });

But when running the test, I get this failed result:

expect(spy).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

  61 |     component.ngOnInit();
  62 | 
> 63 |     expect(userService.publicProperty).toHaveBeenCalled();
     |                                      ^
  64 |     expect(component.me).toBeDefined();
  65 | 
  66 |   });

I'm not sure what I'm doing wrong, has anyone got this to work before?

Upvotes: 0

Views: 1116

Answers (1)

Nichola
Nichola

Reputation: 532

If you just need to make sure that the private method in your component is assigning a value to the publicProperty in the service, you can just use normal expect with the service publicProperty

it('should set user oninit', ()=> {
    let me: Me | User;


    component.ngOnInit();

    expect(userService.publicProperty).toEqual(valueExpected);
    expect(component.me).toBeDefined();

  });

Upvotes: 0

Related Questions