Skip to content

Poor Man's Mocks in TypeScript

March 7th, 2017 - SoftwareTutorial

Today I went against my better judgement of usign a mock framework and decided to create my own mocks to allow coverage testing for an IPC-calling code.

My reference code I wanted to test is:

export class ScanTriggerEvent {
  name: string = 'scan'

  constructor(private pathService: PathsService) {}

  /**
   * Send a scan event to the background scanner
   *
   * @param stream the stream through which we send the message
   */
  execute(stream: any): any {
    logger.debug('ScanTriggerEvent: execute()')
    if (this.pathService) {
      this.pathService.getSourcePaths().then((value: any) => stream.send(this.name, value))
    }
  }
}

The code would use an angular service named PathService which, for the purpose of this test only has a method named getSourcePaths(), which returns a Promise. Now, I needed to emulate that method, and the code I wrote to do that is:

// The service
let service: any = {
  getSourcePaths(): any {
    return {
      then(fun: any): any {
        fun()
      }
    }
  }
}

It basically defines an object containing a method getSourcePaths() which returns another object containing a method named then(fun:any) which accepts a parameter fun and calls it. Simple. In jargon, I’ve implemented an anonymous interface :)

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: