mtsmfm / hubot-test-helper

Helper for testing hubot script
MIT License
115 stars 40 forks source link

Mock dependencies #51

Open joyarzun opened 6 years ago

joyarzun commented 6 years ago

Hi My code looks like:

const myApi = require("./myApi");

robot.respond(/my regex/i,  res => {
      myApi
        .process()
        .then(result => res.send(result.message))
});

myApi is a wrapper for Google Api. So, I want to test mocking my Api. I usually use proxyquire but I don't know because you only pass the path and don't do a require. Do you have any clue?

ghost commented 6 years ago

I was able to mock a dependency of my script by using mockery and sinon. Here's a snippet that shows an example:

const mockery = require('mockery');
const sinon = require('sinon');
const Helper = require('hubot-test-helper');
const co = require('co');

const { expect } = require('chai');

const processFn = sinon.stub();
const mockApi = {
  process: processFn
};

describe('script', () => {
  beforeEach(() => {
    const helper = new Helper('./script.js');
    mockery.registerMock('./myApi'.js, mockApi);
    mockery.enable({ warnOnUnregistered: false });
    this.room = helper.createRoom({ httpd: false });
  });

  afterEach(() => {
    this.room.destroy();
    processFn.reset();
    mockery.disable();
  });

  context('script', () => {
    beforeEach(() => {
      processFn.resolves('Hello!');
      return co(function * () {
        yield this.room.user.say('brian', '@hubot my regex');
      }.bind(this));
    });

    it('returns', () => {
      expect(this.room.messages).to.equal([
        ['brian', '@hubot my regex'],
        ['hubot', 'Hello!']
      ]);
    });
  });
});