Skip to content

Instantly share code, notes, and snippets.

@kozy4324
Created June 12, 2012 03:55
Show Gist options
  • Save kozy4324/2914800 to your computer and use it in GitHub Desktop.
Save kozy4324/2914800 to your computer and use it in GitHub Desktop.
Jasmine-nodeでHTTPリクエストのテスト用モジュール
http = require 'http'
fs = require 'fs'
mixin = (args...) ->
target = {}
for arg in args
target[k] = v for k, v of arg
target
request = (method, url, data, headers, callback) ->
[headers, callback] = [{}, headers] if typeof headers is 'function'
# url
url.match /(?:http:\/\/)([^:\/]+)(?:(?::)(\d+))?(\/[^\?]+)?/
host = RegExp.$1
port = RegExp.$2 || 80
path = RegExp.$3 || '/'
# headers
_headers = mixin {}, headers
# data
if data?
_data = if data[0] is '@'
fs.readFileSync("#{__dirname}/#{data[1..]}", 'utf8').replace /[\n\r]+$/, ''
else
data
_headers['Content-Length'] = Buffer.byteLength _data, 'utf8'
# options
options =
host: host
port: port
path: path
method: method
headers: _headers
req = http.request options, (res) ->
buf = []
res.setEncoding 'utf8'
res.on 'data', (chunk) ->
buf.push chunk
res.on 'end', ->
callback
statusCode: res.statusCode
headers: res.headers
data: buf.join ''
req.on 'error', (e) ->
console.error "problem with request: #{e}"
callback
statusCode: null
headers: {}
data: null
req.write _data if data?
req.end()
get = (url, headers, callback) -> request 'GET', url, null, headers, callback
post = (url, data, headers, callback) -> request 'POST', url, data, headers, callback
form_post = (url, data, headers, callback) ->
[headers, callback] = [{}, headers] if typeof headers is 'function'
post url, data, mixin(headers, {'Content-Type': 'application/x-www-form-urlencoded'}), callback
# for jasmine
impl_waits = (originFunc) ->
() ->
args = arguments
[rest..., originCallback] = args
flg = false
callback = (res) ->
originCallback res
flg = true
runs -> originFunc.apply this, rest.concat callback
waitsFor -> flg
get.and_waits = impl_waits get
post.and_waits = impl_waits post
form_post.and_waits = impl_waits form_post
# exports
module.exports =
get: get
post: post
form_post: form_post
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment