简体   繁体   中英

Angular unit test SwitchMap not working

I have the following method in a service:

login(username: string, password: string): Observable<any> {

  console.log('BEFORE switchMap');

  return this.webApiService.authenticate(username, password).pipe(switchMap((x) => {

    console.log('AFTER switchMap');

    return this.webApiService.getMe().pipe(switchMap((me) => {

      // ... Code removed for brevity ...

      this.isAuthenticatedField = true;

      return of(me);
    }));
  }));
}

NOTE: webApiService is just a angular service that wraps our web service API.

This is being tested with the following test (mocking the web service):

  it('should should set isAuthenticated on successful login', inject([AuthenticationService], (service: AuthenticationService) => {
    webApiSpy.authenticate.and.returnValue(of({}));
    webApiSpy.getMe.and.returnValue(of(me));
    service.login('testusername', 'secretpassword');
    expect(service.isAuthenticated).toEqual(true);
  }));

When I run this in the browser everything is working fine. However when I run this in my test, I get the 'BEFORE switchMap' line printed to the console but I never get the 'AFTER switchMap'.

As Harry Ninh kindly pointed out, I needed to subscribe to the observable like so:

  it('should should set isAuthenticated on successful login', inject([AuthenticationService], (service: AuthenticationService) => {
    webApiSpy.authenticate.and.returnValue(of({}));
    webApiSpy.getMe.and.returnValue(of(me));
    service.login('testusername', 'secretpassword').then(() => {
      expect(service.isAuthenticated).toEqual(true);
    });   
  }));

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