Poor Man's Mocks in TypeScript
1 min read

Poor Man's Mocks in TypeScript

Poor Man's Mocks in TypeScript

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 {

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 :)