all files / core/spying/ spy.ts

100% Statements 25/25
100% Branches 4/4
100% Functions 7/7
100% Lines 24/24
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                 56× 124×     56× 56×       90×   90×   90× 87×     90× 16×     74×     16× 16×              
import { SpyCall } from "./spy-call";
 
export class Spy {
 
  private _originalFunction: (...args: Array<any>) => any;
  private _returnValue: any;
  private _hasReturnValue: boolean;
  private _isStubbed: boolean;
  private _originalContext: any;
 
  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);
    }
 
    if (this._hasReturnValue) {
      return this._returnValue;
    }
 
    return returnValue;
  }
 
  public return(returnValue: any) {
    this._returnValue = returnValue;
    this._hasReturnValue = true;
  }
 
  public andCallThrough() {
    this._isStubbed = false;
  }
 
  public andStub() {
    this._isStubbed = true;
  }
 
}