mock responses

This commit is contained in:
Lloyd Brookes
2015-11-19 16:03:01 +00:00
parent b46b197a9f
commit 85686e67b5
6 changed files with 110 additions and 30 deletions

View File

@ -3,7 +3,7 @@ const path = require('path')
const http = require('http')
const url = require('url')
const arrayify = require('array-back')
let debug
let debug, pathToRegexp
/**
* @module local-web-server
@ -57,7 +57,7 @@ function localWebServer (options) {
const convert = require('koa-convert')
const cors = require('kcors')
const _ = require('koa-route')
const pathToRegexp = require('path-to-regexp')
pathToRegexp = require('path-to-regexp')
debug = require('debug')('local-web-server')
const log = options.log
@ -70,9 +70,6 @@ function localWebServer (options) {
function verbose (category, message) {
if (options.verbose) {
debug(category, message)
// process.nextTick(() => {
// app.emit('verbose', category, message)
// })
}
}
app._verbose = verbose
@ -93,8 +90,9 @@ function localWebServer (options) {
app.use(_.all(route.from, proxyRequest(route, app)))
} else {
const rewrite = require('koa-rewrite')
verbose('local rewrite', `${route.from} -> ${route.to}`)
app.use(rewrite(route.from, route.to))
const mw = rewrite(route.from, route.to)
mw._name = 'rewrite'
app.use(mw)
}
}
})
@ -110,7 +108,6 @@ function localWebServer (options) {
if (!options['no-cache']) {
const conditional = require('koa-conditional-get')
const etag = require('koa-etag')
// verbose('etag caching', 'enabled')
app.use(conditional())
app.use(etag())
}
@ -239,11 +236,39 @@ function mockResponses (options) {
return function mockResponses (ctx, next) {
if (/\.mock.js$/.test(ctx.path)) {
const mocks = arrayify(require(path.join(options.root, ctx.path)))
const mock = mocks.find(mock => {
return !mock.request || mock.request.method === ctx.method
const testValue = require('test-value')
const t = require('typical')
/* find a mock with compatible method and accepts */
let mock = mocks.find(mock => {
return testValue(mock, {
request: {
method: [ ctx.method, undefined ],
accepts: type => ctx.accepts(type)
}
})
})
Object.assign(ctx.response, mock.response)
options.verbose('mock response', JSON.stringify(mock.response), JSON.stringify(ctx.response))
/* else take the first mock without a request (no request means 'all requests') */
if (!mock) {
mock = mocks.find(mock => !mock.request)
}
const mockedReponse = {}
/* resolve any functions on the mock */
Object.keys(mock.response).forEach(key => {
if (t.isFunction(mock.response[key])) {
mockedReponse[key] = mock.response[key](ctx)
} else {
mockedReponse[key] = mock.response[key]
}
})
if (mock) {
Object.assign(ctx.response, mockedReponse)
options.verbose('mocked response', JSON.stringify(mockedReponse))
options.verbose('actual response', JSON.stringify(ctx.response))
}
} else {
return next()
}