SinonでNode.jsのテストを書くときにuseFakeXMLHttpRequestが使えなくて困った

題名通り、Mocha/SinonでNode.jsのテストを書いているのですが、どうやらNode.jsの場合はuseFakeXMLHttpRequestとかFakeServerが使えないようです。

APIのテストとかもやりたいので困ったなぁと思っていたのですが、どうやらSinonのGithubを見るとだいぶ前にIssueとして挙げられてそのまま放置されているようです。
https://github.com/cjohansen/Sinon.JS/issues/21

結局どーした?

しょうがないのでStubで回避することにしました。上のIssueにも解決策として「httpをラップしやがれ」みたいなことが書いてあるので、見当外れではないでしょう。

コードはこんな感じ

http = require 'http'

class Sample
  constructor: ->
  sampleRequest: (options) ->
    req = http.request options, (res) ->
      # なんかほげほげ
    req.end()

module.exports = new Sample()

テストがこんな感じ

http = require 'http'
events = require 'events'
sample = require './sample.js'

describe 'test for http mock', ->
  beforeEach (done) ->
    @requests = []
    @stub = sinon.stub http, 'request', (options, callback) =>
      @requests.push options
      # response mock object
      res = new events.EventEmitter()
      res.setEncoding = ->
      callback res
      # comment in following codes if use data, end and error event
      # res.emit 'data', {}
      # request mock object
      req = new events.EventEmitter()
      req.end = ->
      req

    done()

  afterEach (done) ->
    @stub.restore()

  it 'should push request options in @requests when http#request is called', (done) ->
    sample.sampleRequest {}
    @requests.length.should 1
    done()   

成功/失敗用のstubを用意しておけばだいたい用が足りる感じですかね。
もっとパターンをつけたい場合はstubの中身をテストごとにいじりやすいようにしておく必要がありそうです。