Skip to content

Instantly share code, notes, and snippets.

@joliveros
Last active January 17, 2017 19:33
Show Gist options
  • Save joliveros/710aca623d7de3f91ea08b1d9a46ff59 to your computer and use it in GitHub Desktop.
Save joliveros/710aca623d7de3f91ea08b1d9a46ff59 to your computer and use it in GitHub Desktop.

Example Controller

import { Request, Response } from 'express';
import MessageSender form '../Services/MessageSender';

/**
 * Example controller that provides a healthcheck endpoint
 */
module Example {

  'use strict';

  /*
   * Return an empty 200 response
   */
  export function someMethod (req: Request, res: Response) {
    // this is where you can inject your mock
    const messageSender = this._messageSender || new MessageSender(); 
    
    messageSender.SendMessage("hello world!")
      .then(() => res.end);
  }

}

export = Example;

Example Controller Tests

import sinon from 'sinon';
import sinonStubPromise from 'sinon-stub-promise';
import { someMethod } from './Example';

sinonStubPromise(sinon);

describe('Example Controller', () => {
  describe('someMethod', () => {
    it('should send a message', () => {
      const sendMessagePromise = sinon.stub().returnsPromise();
      
      const messageSenderMock = {
        sendMessage: (message) => {
          sendMessagePromise.resolves({sid: 'MSXXXXXXXXXXXXXXXXXXXXXXXXX', body: message});
        }
      };
      
      
      someMethod._messageSender = messageSenderMock;
      
      someMethod({}, {});
      
      expect(sendMessagePromise.resolved).to.eql({sid: 'MSXXXXXXXXXXXXXXXXXXXXXXXXX', body: 'hello world!'});
    });  
  })
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment