简体   繁体   中英

How unit-test declarative approach in angular

Here is my issue, I want to find a way to do a unit test this code and to check if the connected user is my specificClient? I have a 2 service layers the UserService and UserClient as shown:

    export class UserClient {
  
    getConnectedUser(): Observable<User> {
        return this.http.get<User>(URL + '/me').pipe(shareReplay(1));
  }




 export class UserService {

  public connectedUser$: Observable<User> = this.userClient.getConnectedUser();
  constructor(private userClient: UserClient) {
  }

  isSpecificClient(): Observable<boolean> {
    return this.connectedUser$.pipe(
      map(user => user.authorities
                           .find(authorized => authorized.authority === Autorite.CLIENT) != null
      )
    );
  }

Angular official documentation provided a guideline for testing HTTP requests .

If you focus only UserService , another option would be spying on UserClient :

import { of } from 'rxjs';

let userClient: UserClient;
let userService: UserService;

// TestBed.configureTestingModule is omitted...

beforeEach(() => {
  userClient = TestBed.inject(UserClient);
  userService = TestBed.inject(UserService);
});

it ('should do something...', () => {

  spyOn(userClient, 'getConnectedUser').and.returnValue(of(new User(...));
  
  userService.isSpecificClient().subscribe(value => {
    
    expect(value).toBeFalsy(); // your expectation goes here...
  });
});

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