Search code examples
angularpromiserxjsreturn

what types do "toPromise()" exist on in order to create mock?


I have code I cannot edit and code I can.

the code I can't edit is the following :

this.getLogs()
    .toPromise()
    .then((resp: any) => ({
      data: resp['results'],
      totalCount: resp['count']
}));

the code I can edit is the following.

  private getLogs() {
    if (this.id) { // I added this
      params = {};
      params['log_id'] = this.id;
      const url = `${AppGlobal.API_URL}${thislogsUrl}`;
      return this.http.post(
        url,
        params,
        this.authService.getRequestOptions()
      ).pipe(catchError(error => this.handleError(error)));
    } else {  // I added this
      return <---- What do I put here????
    }
  }

I can't for the all the googling in the world find what I am supposed to put on that return that would make the code I can't edit happy.

whatever I return must have the type "toPromise()". but I don't actually want to make an api call in that case (the case where I'm missing the parameter)

I've tried :

  1. return new Observable(string ).delay(500);
  2. return new Promise(null);
  3. return Rx.Observable.of('o').delay(500);
  4. not returning

but none of these are even correct syntax on their own.

The bottom line is I don't want to get an error state. I want it to be silent in that case. preferably do nothing.


Solution

  • toPromise() method exists on Observable class so you have to return an Observable. Since you need to turn it into Promise you can return for example EMPTY that will be turned into a Promise that resolves immediately with value undefined.

    You can use eventually of(undefined) as well.