LoginSignup
4
2

More than 5 years have passed since last update.

Webhook で動作する Hubot をテストする (mocha, chai, hubot-test-helper)

Last updated at Posted at 2016-10-14

HTTP POST リクエストを受信すると動作する Hubot をテストする。

  • Hubot をテストするには hubot-test-helper が便利
  • CoffeeScript 書いたテストを mocha で動かすには --compilers オプションが必要
  • npm test でテストを実行するには package.json に scripts を書く
  • HTTP POST を送信するには request が楽だけど、json を送る時には注意が必要

テスト対象の Hubot

POST /hello/hook?room=<部屋ID> を受信すると、リクエストボディから名前を取得して、挨拶メッセージを作り、部屋へ送信する。

module.exports = (robot) ->
  robot.router.post "/hello/hook", (req, res) ->
    room = req.query.room
    announceMessage req, (what) ->
      robot.messageRoom room, what 
    res.end "ok"

  announceMessage = (req, cb) ->
    cb 'Hello, ' + req.body.name

事前準備

パッケージ構成

.
├── package.json
├── scripts
│   └── hook.coffee
├── tests
│   └── test-hook.coffee
...

npm

mocha, chai, hubot-test-helper をインストールする

$ npm install mocha chai hubot-test-helper --save-dev

mocha で CoffeeScript を動かすために、compilers オプションが必要。また、

$ npm test

でテストを実行するために、package.json に scripts を追記する。

...
    "scripts": {
        "test": "mocha 'tests/**/*.coffee' --compilers coffee:coffee-script"
    }
...

テストの書き方

Webhook を HTTP GET で起動するテストは
https://github.com/mtsmfm/hubot-test-helper/blob/master/test/httpd-world_test.coffee
が参考になる。

HTTP POST を送信する場合は、以下に注意する。

  • http ではなく request で起動する方が楽。
  • ただし JSON を渡す場合、reuqest.post() ではなく、request() を使う。json: true の指定が必要。
Helper = require('hubot-test-helper')
helper = new Helper('../scripts')
{assert} = require('chai')
request = require('request')

process.env.EXPRESS_PORT = 8080

describe 'hello-webhook', ->
  beforeEach ->
    @robot = helper.createRoom()

  afterEach ->
    @robot.destroy()

  context 'POST /hello/hook', ->
    beforeEach (done) ->
      request {method: 'POST', url: 'http://localhost:8080/hello/webhook?room=12345', json: true, body: {name: 'takatama'}},
        (@error, @response, @body) => done()

    it 'responds with status 200', ->
      assert.equal @response.statusCode, 200
      assert.equal @body, 'ok'
      assert.deepEqual @robot.messages, [['hubot', 'Hello, takatama']]

テストを実行するには

$npm test
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2