简体   繁体   中英

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?

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

  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM