Skip to content

Instantly share code, notes, and snippets.

@rcollette
Created April 24, 2020 15:56
Show Gist options
  • Save rcollette/51174165c96fb0d6ceeda35074f934ea to your computer and use it in GitHub Desktop.
Save rcollette/51174165c96fb0d6ceeda35074f934ea to your computer and use it in GitHub Desktop.
A Typescript Class Used to Mock Promises in Unit Tests
// tslint:disable-next-line:no-any
export class PromiseResolver<T = any> {
private _resolve: (value?: T | PromiseLike<T>) => void;
// tslint:disable-next-line:no-any
private _reject: (reason?: any) => void;
// tslint:disable-next-line:no-any
public executor = (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => {
this._resolve = resolve;
this._reject = reject;
};
public createPromise(): Promise<T> {
return new Promise<T>(this.executor);
}
public resolve(value?: T | PromiseLike<T>): void {
this._resolve(value);
}
// tslint:disable-next-line:no-any
public reject(reason?: any): void {
this._reject(reason);
}
}
@rcollette
Copy link
Author

const resolver = new PromiseResolver<void>;
someSpyObj.someFunc.and.returnValue(resolver.createPromise());
// ... some time later
resolver.resolve();

@rcollette
Copy link
Author

rcollette commented Apr 24, 2020

Done this way because this is not possible.

// tslint:disable-next-line:no-any
export class MockPromise<T = any> extends Promise<T> {
  private _resolve: (value?: T | PromiseLike<T>) => void;
  // tslint:disable-next-line:no-any
  private _reject: (reason?: any) => void;

  constructor() {
    // tslint:disable-next-line:no-any
    super((resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => {
      // this is undefined here.
      this._resolve = resolve;
      this._reject = reject;
    });
  }

  public resolve(value?: T | PromiseLike<T>): void {
    this._resolve(value);
  }

  // tslint:disable-next-line:no-any
  public reject(reason?: any): void {
    this._reject(reason);
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment