Webhook で動作する Hubot をテストする (mocha, chai, hubot-test-helper)
9287 ワード
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
.
├── package.json
├── scripts
│ └── hook.coffee
├── tests
│ └── test-hook.coffee
...
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
Author And Source
この問題について(Webhook で動作する Hubot をテストする (mocha, chai, hubot-test-helper)), 我々は、より多くの情報をここで見つけました https://qiita.com/takatama/items/e3a928efed71f0f604b9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .