superagentモジュールでAPI Gatewayのテストをする
API Gatewayのテストをする時にPOSTMANやVSCodeのRest Clientプラグインなどがありますが、mochaからsuperagentモジュールを使ってAPIを叩いて、その結果を確認することができます。
プロキシ設定が必要な場合はsuperagent-proxyモジュールも使用します。
const superagent = require('superagent')
require('superagent-proxy')(superagent)
const proxy = process.env.http_proxy || 'http://プロキシ.co.jp:8080/'
describe('test', () => {
it('APIのテスト', async () => {
superagent
.post(
'https://api.example.com/companys/12/employId/1' // API URL
)
.proxy(proxy)
.send({ // リクエストボディ部
body: 'body'
})
.set('accept', 'json') // ヘッダ部
.end((err, res) => { // callback
assert.deepEqual(res.body, {
name: 'takahashi',
age: 22
})
})
})
このテストと似たようなことがVSCodeのRest Clientでも可能です。
Promise化
Promise化したい場合は、endメソッドを省略してawaitするだけです。
const ret = await superagent
.post(
'https://confrage-webhooktest.free.beeceptor.com/test'
)
.send({
body: 'body'
})
.set('Content-Type', 'application/json')
console.log(ret)
}
superagentはasync/awaitをサポートしています。
Site not found · GitHub Pages
timeout
superagentでAPIを叩いたときにtimeoutメソッドでタイムアウトを設定します。
index.js
const superagent = require('supreagent')
(async function() {
try {
const response = await superagent
.get(
'http://localhost:8080/sleep/5'
)
.timeout(6000) // ミリ秒で指定するので、6秒
.set('accept', 'json')
.send({})
} catch(err) {
console.log(err)
}
})()
※node.js v14

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^


コメント