jeudi 6 juin 2019

How to mock a "nested" angular service used in a component with jest

I want to write a unit test for an Angular (~v7.2.0) Component with Jest (^v24.8.0).

This is the component, it's using the nested service via this.api.manageUser.getUsersStats() and i want to check if this is ever called and mock the result. So best thing would be to able to write a "global" / "manual" mock in a "mocks"-folder.

I already tried a lot of things, but none works as expected.

I really hope somebody can help me!

// users.component

import { TstApiService } from '../../services/TstApi/TstApi.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.sass']
})
export class UsersComponent implements OnInit, OnDestroy {
  constructor(
    // ...
    private api: TstApiService
    ) { }

  ngOnInit() {
    this.getUsersStats();
  }

  private getUsersStats() {
    this.api.manageUser.getUsersStats().pipe(take(1)).subscribe(userStats => {
      /* ... */ = userStats.allUsers
    })
  }
}

This is my Service:

// TstApi.service

import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TstApiService {
    private http: TstHttp
    manageUser: ManageUser

    constructor(private httpClient: HttpClient) {
        this.http = new TstHttp(this.httpClient)
        this.manageUser = new ManageUser(this.http)
     }
}

class ManageUser {
    constructor(private http: TstHttp) {}
    getUsersStats(): Observable<TUserStats> { //<-- this is the function used by the component
      return this.http.get('/manage/user/stats')
    }
}

class TstHttp {
    private apiUrl: string
    constructor(private http: HttpClient) {
        this.apiUrl = environment.apiBaseUrl
    }
    /**
     * @throws{ApiError}
     * @throws{Error}
     */
    get<T>(path: string): Observable<T> {
      return this.http.get<T>(environment.apiBaseUrl + path)
    }
}

Aucun commentaire:

Enregistrer un commentaire