GithubHelp home page GithubHelp logo

mtsmfm / hubot-test-helper Goto Github PK

View Code? Open in Web Editor NEW
115.0 6.0 41.0 73 KB

Helper for testing hubot script

License: MIT License

CoffeeScript 4.57% JavaScript 95.43%
hubot coffeescript hubot-scripts

hubot-test-helper's Introduction

Hubot test helper

Build Status

Helper for testing Hubot script.

Install

npm install hubot-test-helper --save-dev

Usage

If you have a following hubot script:

module.exports = robot =>
  robot.respond(/hi$/i, msg => msg.reply('hi'))

You can test it like:

const Helper = require('hubot-test-helper');
// helper loads all scripts passed a directory
const helper = new Helper('./scripts');

// helper loads a specific script if it's a file
const scriptHelper = new Helper('./scripts/specific-script.js');

const co     = require('co');
const expect = require('chai').expect;

describe('hello-world', function() {
  beforeEach(function() {
    this.room = helper.createRoom();
  });
  afterEach(function() {
    this.room.destroy();
  });

  context('user says hi to hubot', function() {
    beforeEach(function() {
      return co(function*() {
        yield this.room.user.say('alice', '@hubot hi');
        yield this.room.user.say('bob',   '@hubot hi');
      }.bind(this));
    });

    it('should reply to user', function() {
      expect(this.room.messages).to.eql([
        ['alice', '@hubot hi'],
        ['hubot', '@alice hi'],
        ['bob',   '@hubot hi'],
        ['hubot', '@bob hi']
      ]);
    });
  });
});

HTTPD

By default Hubot enables a built in HTTP server. The server continues between tests and so requires it to be shutdown during teardown using room.destroy().

This feature can be turned off in tests that don't need it by passing using helper.createRoom(httpd: false).

See the tests for an example of testing the HTTP server.

Manual delay

Sometimes we can't access callback actions from a script. Just like in real use-case we may have to wait for a bot to finish processing before replying, in testing we may anticipate the delayed reply with a manual time delay.

For example we have the following script:

module.exports = robot =>
  robot.hear(/(http(?:s?):\/\/(\S*))/i, res => {
    const url = res.match[1];
    res.send(`ok1: ${url}`);
    robot.http(url).get()((err, response, body) => res.send(`ok2: ${url}`));
  });

To test the second callback response "ok2: ..." we use the following script:

const Helper = require('hubot-test-helper');
const helper = new Helper('../scripts/http.js');

const Promise = require('bluebird');
const co      = require('co');
const expect  = require('chai').expect;

// test ping
describe('http', function() {
  beforeEach(function() {
    this.room = helper.createRoom({httpd: false});
  });

  // Test case
  context('user posts link', function() {
    beforeEach(function() {
      return co(function*() {
        yield this.room.user.say('user1', 'http://google.com');
        // delay one second for the second
        // callback message to be posted to @room
        yield new Promise.delay(1000);
      }.bind(this));
    });

    // response
    it('expects deplayed callback from ok2', function() {
      console.log(this.room.messages);
      expect(this.room.messages).to.eql([
        ['user1', 'http://google.com'],
        ['hubot', 'ok1: http://google.com'],
        ['hubot', 'ok2: http://google.com']
      ]);
    });
  });
});

Note that yield and generators are part of ECMA6, so it may not work on older node.js versions. It will wait for the delay to complete the beforeEach before proceeding to the test it.

Testing messages sent to other rooms

You can also test messages sent by your script to other rooms through Hubot's robot.messageRoom(...) method.

Given the following script:

module.exports = robot =>
  robot.respond(/announce otherRoom: (.+)$/i, msg => {
    robot.messageRoom('otherRoom', "@#{msg.envelope.user.name} said: #{msg.msg.match[1]}");
  })

you could test the messages sent to other rooms like this:

const Helper = require('../src/index');
const helper = new Helper('../scripts/message-room.js');

const expect = require('chai').expect;

describe('message-room', function() {
  beforeEach(function() {
    this.room = helper.createRoom({name: 'room', httpd: false});
  });

  context('user asks hubot to announce something', function() {
    beforeEach(function() {
      return co(function*() {
        yield this.room.user.say('alice', '@hubot announce otherRoom: I love hubot!');
      }.bind(this));
    });

    it('should not post to this channel', function() {
      expect(this.room.messages).to.eql([
        ['alice', '@hubot announce otherRoom: I love hubot!']
      ]);
    });

    it('should post to the other channel', function() {
      expect(this.room.robot.messagesTo['otherRoom']).to.eql([
        ['hubot', '@alice says: I love hubot!']
      ]);
    });
  });
});

Testing events

You can also test events emitted by your script. For example, Slack users may want to test the creation of a message attachment.

Given the following script:

module.exports = robot =>
  robot.respond(/check status$/i, msg =>
    robot.emit('slack.attachment', {
      message: msg.message,
      content: {
        color: "good",
        text: "It's all good!"
      }
    })
  )

you could test the emitted event like this:

const Helper = require('hubot-test-helper');
const helper = new Helper('../scripts/status_check.js');

const expect = require('chai').expect;

describe('status check', function() {
  beforeEach(function() {
    this.room = helper.createRoom({httpd: false});
  });

  it('should send a slack event', function() {
    let response = null;
    this.room.robot.on('slack.attachment', event => response = event.content);

    this.room.user.say('bob', '@hubot check status').then(() => {
      expect(response.text).to.eql("It's all good!");
    });
  });
});

Development

Requirements

  • docker
  • docker-compose

Setup

git clone https://github.com/mtsmfm/hubot-test-helper
cd hubot-test-helper
docker-compose up -d
docker-compose exec app bash
yarn install

Run test

yarn run test

Debug

yarn run test-unit-debug

Above command will output:

yarn run v0.18.1
$ mocha --inspect --debug-brk --compilers coffee:coffee-script/register test
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
    chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/59631086-0a0c-424b-8f5b-8828be123894

Then open chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/59631086-0a0c-424b-8f5b-8828be123894 in Chrome.

hubot-test-helper's People

Contributors

akatz avatar alfred-nsh avatar amussey avatar atmos avatar davidalpert avatar floby avatar halkeye avatar harlantwood avatar kengz avatar miaonster avatar mtsmfm avatar pchaigno avatar sukima avatar technicalpickles avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

hubot-test-helper's Issues

Allow user to require the Hubot script themselves

I have a script which is using res.random. Obviously that's hard to test for, so I want to use proxyquire to override the require that gets the possible responses, such that there's only one possible response. However I can't do this because hubot-test-helper is calling require() for me.

It'd be nice if I could just pass in a function and have that interpreted by hubot-test-helper as the plugin itself, pre-require()'d.

support testing one robot (shared brain) present in multiple rooms

not sure about other implementations, but in slack, hubot can be in multiple rooms (channels), but there is only one instance of the robot and brain

is there a way to test this functionality with the current test-helper and I'm missing it?

if not, can we add on this functionality? i'd be glad to implement and PR with some guidance, but at this point I don't quite have a lot of background on test-helper or hubot architecture.

thanks!
Matt

error running test: Error: Cannot find module 'hubot-test-helper'

Hi,

I am getting the following error when I try to run my test. It appears to be an issue with version 1.4 as I was able to run on 1.3.

Here is the error I get:

module.js:339
    throw err;
    ^

Error: Cannot find module 'hubot-test-helper'
  at Function.Module._resolveFilename (module.js:337:15)
  at Function.Module._load (module.js:287:25)
  at Module.require (module.js:366:17)
  at require (module.js:385:17)
  at Object.<anonymous> (/Users/monica/development/mozilla/webqabot/test/test_webqa.coffee:1:10)
  at Object.<anonymous> (/Users/monica/development/mozilla/webqabot/test/test_webqa.coffee:1:1)
  at Module._compile (module.js:435:26)
  at Object.loadFile (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/register.js:16:19)
  at Module.load (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/register.js:45:36)
  at Function.Module._load (module.js:311:12)
  at Module.require (module.js:366:17)
  at require (module.js:385:17)
  at /usr/local/lib/node_modules/mocha/lib/mocha.js:216:27
  at Array.forEach (native)
  at Mocha.loadFiles (/usr/local/lib/node_modules/mocha/lib/mocha.js:213:14)
  at Mocha.run (/usr/local/lib/node_modules/mocha/lib/mocha.js:453:10)
  at Object.<anonymous> (/usr/local/lib/node_modules/mocha/bin/_mocha:393:18)
  at Module._compile (module.js:435:26)
  at Object.Module._extensions..js (module.js:442:10)
  at Module.load (module.js:356:32)
  at Function.Module._load (module.js:311:12)
  at Function.Module.runMain (module.js:467:10)
  at startup (node.js:136:18)
  at node.js:963:3

Here are the first few lines of my test:

Helper = require('hubot-test-helper')
helper = new Helper('../scripts/webqa.coffee')
chai = require 'chai'
expect = chai.expect

I invoke my test from the command line by doing the following:

mocha --compilers "coffee:coffee-script/register" test/test_webqa.coffee

My package.json has the following, which will install hubot-test-helper version 1.4

 "devDependencies": {
    "chai": "^3.4.1",
    "hubot-test-helper": "^1.3.0",
    "mocha": "^2.3.4",
    "coffee-script": "^1.9.3"
  }

However, if I change my package.json to explicitly use version 1.3, then my tests run and pass. Example:

"devDependencies": {
    "chai": "^3.4.1",
    "hubot-test-helper": "1.3.0",
    "mocha": "^2.3.4",
    "coffee-script": "^1.9.3"
  }

Doesn't seem to work with custom listeners?

I'm getting an error:

TypeError: bot.listen is not a function

when using this in conjunction with hubot-conversation, which uses a custom listener.

I'll try to come up with the smallest working example of the problem...

running node 6.9.2 'yield' is reserved

trying to get the tests to run on node 6.9.2 and all im getting is:

`Running "mochaTest:test" (mochaTest) task

Mocha exploded!
SyntaxError: reserved word "yield"
at exports.throwSyntaxError (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/coffee-script/lib/coffee-script/helpers.js:197:13)
at Lexer.exports.Lexer.Lexer.error (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/coffee-script/lib/coffee-script/lexer.js:778:14)
at Lexer.exports.Lexer.Lexer.identifierToken (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/coffee-script/lib/coffee-script/lexer.js:102:16)
at Lexer.exports.Lexer.Lexer.tokenize (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/coffee-script/lib/coffee-script/lexer.js:30:25)
at compile (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/coffee-script/lib/coffee-script/coffee-script.js:35:36)
at Object.loadFile (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/coffee-script/lib/coffee-script/coffee-script.js:176:14)
at Module.load (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/coffee-script/lib/coffee-script/coffee-script.js:211:36)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at /Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/mocha/lib/mocha.js:220:27
at Array.forEach (native)
at Mocha.loadFiles (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/mocha/lib/mocha.js:217:14)
at MochaWrapper.run (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt-mocha-test/tasks/lib/MochaWrapper.js:51:15)
at /Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt-mocha-test/tasks/mocha-test.js:86:20
at capture (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt-mocha-test/tasks/mocha-test.js:33:5)
at Object. (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt-mocha-test/tasks/mocha-test.js:81:5)
at Object. (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt/lib/grunt/task.js:264:15)
at Object.thisTask.fn (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt/lib/grunt/task.js:82:16)
at Object. (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt/lib/util/task.js:301:30)
at Task.runTaskFn (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt/lib/util/task.js:251:24)
at Task. (/Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt/lib/util/task.js:300:12)
at /Users/Thomas/Documents/code/node/hubot-gocd-client/node_modules/grunt/lib/util/task.js:227:11
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
at Module.runMain (module.js:606:11)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3`

robot.http has no effect in tests

It looks like there is an issue with robot.http when using hubot-test-helper. The following script works fine with a Hubot shell but the associated test does not seem to trigger any HTTP request.

Script:

module.exports = (robot) ->
  robot.hear /(http(?:s?):\/\/(\S*))/i, (res) ->
    url = res.match[1]
    res.send "ok1: #{url}"
    robot.http(url).get() (err, response, body) ->
      res.send "ok2: #{url}"

Test:

context "user posts link", ->
    beforeEach ->
      room.user.say 'user1', 'http://google.com'

    it 'hubot posts details about the link', ->
      expect(room.messages).to.eql [
        ['user1', 'http://google.com']
        ['hubot', 'ok1: http://google.com']
        ['hubot', 'ok2: http://google.com']
      ]

room.user.say() and responses are not executed in series...

I tried doing something like this:

    it('should respond in order', function () {
        return room.user.say('user1', '@hubot hi')
            .then(room.user.say('user2', '@hubot hi'))
            .then(function () {
                console.log(room.messages);
            });
    });

My expectation was that it'll say:

user1> @hubot hi
hubot> @user1 hi
user2> @hubot hi
hubot> @user2 hi

Instead I got this:

[ [ 'user1', '@hubot hi' ],
  [ 'user2', '@hubot hi' ],
  [ 'hubot', '@user1 hi' ],
  [ 'hubot', '@user2 hi ] ]

Updating from 1.7.0 to 1.8.1/1.9.0 breaks

Since updating hubot-test-helper from 1.7.0 to 1.8.1 or 1.9.0, my project has been experiencing an odd issue with the sinon stubs we're creating for our hubot scripts. Essentially, we're creating an instance of aws's elasticbeanstalk and verifying a method was called a certain number of times

For example

beforeEach(() => {
      describeEnvironmentsStub = sinon.stub(Object.getPrototypeOf(new aws.ElasticBeanstalk()),
        'describeEnvironments').returns('some environment');
    });

    it('asks for environment information from various elastic beanstalks', async () => {
      await room.user.say('someUser', '@hubot list versions');
      expect(describeEnvironmentsStub.callCount).to.equal(1);
    });

Where the elasticbeanstalk instance is created in the script file outside the module.exports

let devElasticbeanstalk = new aws.ElasticBeanstalk();

module.exports = (robot) => {
  robot.respond(/list versions/, msg => {
    ...where we eventually call devElasticbeanstalk.describeEnvironments.
  });
}

In 1.8.1+, the stub fails to be created and the describeEnvironments function is undefined on the devElasticbeanstalk instance. This isn't the case in 1.7.0.

Any clue into what could be breaking it would be super helpful. Thanks!

Expose the robot logger

My module logs an error message if an environment variable isn't set. However, there's no way to test for that because I can't get access to the robot logger (or it isn't documented). It would be nice if hubot-test-helper would intercept calls to robot.logger.* and allow me to call assertions on logs.

how to mock a specific room/channel

Hi, in my functional code I am using the messageRoom function controlled by a cronjob to post a salutation message each morning.

robot.messageRoom('general', 'hello general room');

How can I mock the 'general' room to provide a test for this functionality?

[Question] Testing adapter-specific send() code

I have a handful of Hubot packages that have a pattern similar to this:

isSlack = robot.adapterName == 'slack'

// ...

if isSlack
  msg.send {
    attachments: [
      {
        text: 'a Slack-specific envelope',
        thumbnail: 'https://example.com/image.png'
        // ...
      }
    ]
  }
else
  msg.send 'regular IRC response'

The trouble is I cannot seem to figure out how to trick the test helper into thinking it has loaded an adapter named 'slack' (I'm only testing the output, so no other capabilities from the adapter are needed). As of right now, I can only write tests against the standard msg.send() response.

Has anyone worked with a similar case?

Room destroy throws error when httpd is false

e.g. (coffeescript)

  beforeEach ->
    @room = helper.createRoom httpd: false

  afterEach ->
    @room.destroy()

Throws TypeError: Cannot read property 'close' of undefined.

I think because .destroy is just a proxy for @robot.server.close() which maybe shouldn't be run if there was no httpd server created? Just guessing, sorry I didn't have time to contribute more.

Mock dependencies

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?

Timeout in beforeEach

I'm trying to run the tests for a number of service. Unfortunately the first test always fails with:

1) ping "before each" hook for "replies pong to user":
  Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

This happens for the first test only - the rest of them pass correctly.
The tests are run under docker based on node:4, with hubot-test-helper between 1.5.1 and latest.

Strangely, this works just fine on local machines and then fails on a buildkite agent. Same container, same versions of dependencies.

The test is just a very simple ping:

expect = require('chai').expect

Helper = require('hubot-test-helper')
helper = new Helper('./../scripts/ping.coffee')

describe 'ping', ->
  room = null

  beforeEach ->
    # Set up the room before running the test
    room = helper.createRoom()

  afterEach ->
    # Tear it down after the test to free up the listener.
    room.destroy()

  context 'user says ping to hubot', ->
    beforeEach ->
      room.user.say 'alice', 'hubot PING'
      room.user.say 'bob',   'hubot PING'

    it 'replies pong to user', ->
      expect(room.messages).to.eql [
        ['alice', 'hubot PING']
        ['bob',   'hubot PING']
        ['hubot', 'PONG']
        ['hubot', 'PONG']
      ]

Any ideas where to look for solutions / what to try are welcome.

test sendPrivate to specific user

Hey,

Is there a way to test when bot initiate a private message ?
ex:

//script
module.exports = (robot) ->
  robot.hear /onboard (@.*)/, (res) ->
    name = res.match[1]
    res.send "Glad to see a new face! Onboarding #{name} right now"
    res.sendPrivate name, "hey #{name} can you tell me your secret password ?"
//test
  it 'initiate a private message to user', ->
    @room.user.say('stephane', 'onboard @arthur 28/10').then =>
      expect(@room.privateMessages).to.eql {
        'arthur': [
          ['hubot', 'hey @arthur can you tell me your secret password ?']
        ]
      }

allow for userId

Most adapters have distinct userName and userId. The constructor here is the default `Hubot.user, which sets the id to the username.

Can we allow for a quick enhancement to set both the username and id? So the argument would be like
receive: (userNameId, message) ->
where userNameId can be a string (back to the original use case), or if it's an array then it shall contain [name, id], which will be set accordingly in the user object.

Testing DMs with hubot

Is there a way to test direct messages with hubot, rather than inside a room with multiple users?

Thank you!

unable to get http tests working

Test code

Helper = require('hubot-test-helper')
expect = require('chai').expect
querystring = require('querystring');
http = require('http')

process.env.EXPRESS_PORT = 8080

# helper loads a specific script if it's a file
helper = new Helper('./../src/scripts/change_is_good.coffee')

describe 'change_is_good', ->
  beforeEach ->
    @room = helper.createRoom()

  afterEach ->
    @room.destroy()

  context 'POST /twobit/change_is_good', ->
    beforeEach (done) ->
      postData = querystring.stringify({issue:{key:"TEST-1"}})

      options = {
        hostname: 'localhost',
        port: 8080,
        path: '/twobit/change_is_good',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': postData.length
        }
      }

      req = http.request options, (@response) => done()
      req.write postData
      req.end

      setTimeout done, 100

    it 'should mention that it received some information about the issue', ->
      expect(@room.privateMessages).to.eql {
        'wesm': [
          ['twobit', 'I received some information about TEST-1']
        ]
      }

Error:

1) change_is_good POST /twobit/change_is_good should mention that it received some information about the issue:
   expected undefined to deeply equal { wesm: [ [ 'twobit', 'I received some information about TEST-1' ] ] }



2) change_is_good "after each" hook for "should mention that it received some information about the issue":
   TypeError: Object #<Room> has no method 'destroy'
  at Context.<anonymous> (test/change_is_good.test.coffee:16:11)

Tests fail due to `async` module in Hubot > 2.14.0

In version 2.14.0, Hubot started using the async module to respond to received messages (in Hubot.Robot). Tests can technically still be run with the current code, but all tests will need to be modified to include a short timeout in the beforeEach function.

    beforeEach (done) ->
      room.user.say 'alice', 'hubot pug me'
      setTimeout done, 50

Another solution would involve replacing the receiver/responder inherited from Robot in MockRobot with the old, synchronous versions (I started investigating this solution, but haven't had time to completely implement it).

Either way, I just wanted to make a quick note of this in case anybody was seeing all of their tests fail.

npm package is jS-incompatible

npm packages published in JS can be used by both JS and coffeescript users; whereas a coffeescript npm package cannot be used inside a .js file. Despite the fact that most hubot users are coffeescript-based, it's good to have a broader compatibility.

I'll include a pull request to address the issue soon. Thanks.

Cannot find module `hubot`

Hey!

I tried using your test helper on an ES6 codebase. I tried to write an integration test with it but just requiring the module fails:

const Helper = require('hubot-test-helper')

I get cannot find module 'hubot'. I don't know what's happening here. I even have hubot in my own package.json. Do you have any clue how to resolve this?

testing exec replies

With a spec:

describe 'hello-world', ->
  beforeEach ->
    @room = helper.createRoom(httpd: false)
  afterEach ->
    @room.destroy()

  context 'user says hi to hubot', (done) ->
    beforeEach ->
      co =>
        yield @room.user.say 'alice', '@hubot hi'
        yield @room.user.say 'bob',   '@hubot hi'

    it 'should reply to user', ->
      console.log(@room.messages)
      expect(@room.messages).to.eql [
        ['alice', '@hubot hi']
        ['hubot', '@alice hi']
        ['bob',   '@hubot hi']
        ['hubot', '@bob hi']
      ]

Then a synchronous reply works as expected:

     robot.respond /hi$/i, (msg) -> 
       msg.reply('hi')

If I change the response to be the stdout of an require('child_process').exec such as:

     robot.respond /hi$/i, (msg) -> 
       @exec = require('child_process').exec
       command = "echo hi"
       @exec command, { shell: '/bin/bash' } , (error, stdout, stderr) ->
         if error
            msg.send "@#{msg.message.user.name} " + "Ops! Not able to run "+ command +" ```" + stderr + "```"
         else
            msg.reply stdout

Then the test fails with only two messages in the room with no responses from hubot. Yet if I run the hubot then the output of @exec command appears as expected.

How do I test code that uses @exec command to generate hubot responses?

Message send in Timeout aren't tracked in room.messages

I do have a function registered which goes like

  robot.respond /hello/i , (msg) ->
    setTimeout () ->
        console.log "Reached timeout"
        msg.send "Hello World!"
    , 1

and I'm expecting this test to succeed:

    it 'should display hello world', ->
      room.user.say('dex', '@hubot hello').then =>
            clock.tick(2)
            console.log "Reached assertion"
            expect(room.messages).to.eql [
                ['dex',   '@hubot hello']        
                ['hubot', 'Hello World!']
            ]

Unfortunately room.messages is missing the response by hubot.
Note: clock.tick(2) is using sion to mock the system time.
To be sure that sion works correctly I added two log statements.
Both of them are executed in my expected order:

Reached timeout
Reached assertion

Help in this matter would be highly appreciated!

Best Sebastian

nothing stored in brain

Hello,

I'd like to test the content of the brain but nothing seems to be stored in it when I run my tests.

packages.json:
{
"name": "...",
"version": "0.1.0",
"private": true,
"author": "...,
"description": "...",
"scripts": {
"test": "mocha --compilers coffee:coffee-script/register tests"
},
"dependencies": {
"hubot": "latest",
"hubot-brain-inspect": "latest",
"hubot-redis-brain": "latest",
"log4js": "latest",
"natural": "latest"
},
"devDependencies": {
"bluebird": "latest",
"chai": "latest",
"coffee-script": "^1.9.3",
"coffeelint": "latest",
"hubot-test-helper": "latest",
"mocha": "latest"
},
"engines": {
"node": "6.1.0"
}
}

test.coffee:
Helper = require('hubot-test-helper')
helper = new Helper('./../scripts')

Promise = require('bluebird')
co = require('co')
expect = require('chai').expect

describe 'hello-world', ->

beforeEach ->
@room = helper.createRoom()

afterEach ->
@room.destroy()

context 'user says hi to hubot', ->
beforeEach ->
co =>
yield @room.user.say('alice', '@...bot hi')

yield @room.user.say('alice', '@...bot trip')

it 'should reply to user', ->
  expect(@room.messages).to.eql [
    ['alice', '@...bot hi']
    ['hubot', '@alice Hello!']
    ['hubot', '@alice Using this bot, you can search for a trip or publish a trip.']
    ['hubot', '@alice If lost: type Help or Stop.']
  ]

STDOUT:
...
[2016-05-16 22:05:15.249] [DEBUG] Message - log_user: brain {"users":{},"_private":{}}
...

hubot ^3.0.0 and hubot-test-helper in JS ES2015

Hi, I'm in the process of writing hubot-test-helper in JavaScript instead of CoffeeScript and support the new Hubot 3.0.0 release which is entirely re-written in JavaScript (ES2015).

Before opening a new repo/npm package I would like to know if you're already working on a pure JavaScript version for this (awesome) helper in order to avoid wasting time and help you with it.

Let me know, thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.