LoginSignup
3
0

More than 5 years have passed since last update.

Nockを触ってみた

Last updated at Posted at 2017-12-07

こんにちは、鈴木です。ネタが思いつかなかったので、今日はhttpをmockingしてくれるnodejsライブライのNockを紹介したいと思います。

ふう、アドベントカレンダーなんとか間に合った。。。

Nock

サードパーティAPIを使っている箇所のテストをするとき、毎回、サードパーティAPIを叩きたくないはずです。もし、そのサードパーティAPIが有料だったら。。。

ってことで、Httpをmockingしてくれるライブラリであるnockを使えば、サードパーティーへのリクエストを疑似的に作ることができるようになります。これによって、何の心配もせずに好きなだけテストを書けるようになのではないでしょうか。

どうやって動いているのか

Node moduleのhttpの関数をオーバーライドしています。なので、httpを使用しているmoduleのリクエストをmockできます。
また、httpsにも対応しています。

インストール

$ npm i —D nock

簡単な例

hogeClient.test.js
import nock from 'nock'
import hogeClient from 'hoge-client'

describe('mock test', () => {
  before(() => {
    // hoge.com/huga?message=Hello でリクエストが来た時、Hiを返す
    nock('http://hoge.com')
      .get('/huga')
      .query({message: 'Hello'})
      .reply(200, 'Hi')
    return
  })

  it('hiが返ってくるか', (done) => {
    hogeClient.get({message: 'Hello'}, (err, res) => {
      assert(res, 'Hi')
      done()
    })
  })
})

基本的なAPI

hostname

const scope = nock('http://example.com')
// or
const scope = nock(/example\.com/)

route

scope.get('/huga').reply(200, 'Hi')
// or
scope.get(/huga/).reply(200, 'Hi')
//or
scope.get((uri) => {
  return true // or false
}).reply('Hi')

request

// get
scope.get('/huga').reply(200, 'Hi')

//post
scope.post('/huga', {
  message: 'Hi'
})

scope.delete('/users', {id: 'huga'})
scope.put('/huga', {})

指定した数だけレスポンス

400回だけレスポンスを返す。それ以降は普通にリクエストを投げてしまう。

scope.get('/huga').times(400).reply(200, 'Hi')

常にレスポンスを返す。

scope.persist().get('/huga').reply(200, 'Hi')

etc

その他、headerを変えたりと色々できますので、そこらはdocumentを参考にしてください。

3
0
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
3
0