all files / core/spying/ spy.ts

100% Statements 32/32
100% Branches 6/6
100% Functions 8/8
100% Lines 31/31
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                   286× 4923×     286× 286×       4661×   4661×   4661× 147×   4514×     4661× 36×     4625×     36× 36×         161× 161×        
import { SpyCall } from "../_spying";
 
export class Spy {
 
  protected originalFunction: (...args: Array<any>) => any;
  private _returnValue: any;
  private _hasReturnValue: boolean;
  private _isStubbed: boolean;
  private _originalContext: any;
  private _fakeFunction: Function;
 
  private _calls: Array<SpyCall> = [];
  public get calls() {
    return this._calls;
  }
 
  public constructor(originalFunction: (...args: Array<any>) => any, originalContext: any) {
    this.originalFunction = originalFunction;
    this._originalContext = originalContext;
  }
 
  public call(args: Array<any>) {
 
    this.calls.push(new SpyCall(args));
 
    let returnValue: any;
 
    if (!this._isStubbed) {
      returnValue = this.originalFunction.apply(this._originalContext, args);
    }
    else if (this._fakeFunction) {
      this._fakeFunction.apply(this._originalContext, args);
    }
 
    if (this._hasReturnValue) {
      return this._returnValue;
    }
 
    return returnValue;
  }
 
  public andReturn(returnValue: any) {
    this._returnValue = returnValue;
    this._hasReturnValue = true;
  }
 
  public andCallThrough() {
    this._isStubbed = false;
    this._fakeFunction = undefined;
  }
 
  public andStub() {
    this._isStubbed = true;
    this._fakeFunction = undefined;
  }
 
  public andCall(fakeFunction: Function) {
    this._isStubbed = true;
    this._fakeFunction = fakeFunction;
  }
}