Jonatan Nilsson
01a916eb2d
All checks were successful
continuous-integration/appveyor/branch AppVeyor build succeeded
102 lines
2 KiB
JavaScript
102 lines
2 KiB
JavaScript
import { spy } from 'eltro'
|
|
|
|
const indexMap = [
|
|
'firstCall',
|
|
'secondCall',
|
|
'thirdCall',
|
|
]
|
|
|
|
export function fakeHttp(inj1, inj2, inj3) {
|
|
let intermediate = {
|
|
createServer: function(cb) {
|
|
if (inj1) inj1(cb)
|
|
intermediate.fakeRequest = cb
|
|
return {
|
|
listen: function(port, ip, cb) {
|
|
if (inj2) inj2(port, ip, cb)
|
|
else if (cb) cb()
|
|
},
|
|
on: function(name, handler) {
|
|
if (inj3) inj3(name, handler)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return intermediate
|
|
}
|
|
|
|
export function createReq(def) {
|
|
return defaults(def, {
|
|
headers: {},
|
|
on: spy(),
|
|
})
|
|
}
|
|
|
|
export function createRes(def) {
|
|
return defaults(def, {
|
|
statusCode: 0,
|
|
end: spy(),
|
|
setHeader: spy(),
|
|
write: spy(),
|
|
on: spy(),
|
|
writeHead: spy(),
|
|
pipe: spy(),
|
|
})
|
|
}
|
|
|
|
export function createCtx(def = {}, endHandler = null) {
|
|
return defaults(def, {
|
|
req: createReq(),
|
|
res: createRes({ end: endHandler || spy() }),
|
|
finished: false,
|
|
method: 'GET',
|
|
url: '/test',
|
|
search: '',
|
|
state: {},
|
|
status: 200,
|
|
body: null,
|
|
type: null,
|
|
length: null,
|
|
headers: {},
|
|
log: {
|
|
error: spy(),
|
|
info: spy(),
|
|
warn: spy(),
|
|
debug: spy(),
|
|
}
|
|
})
|
|
}
|
|
|
|
// taken from isobject npm library
|
|
function isObject(val) {
|
|
return val != null && typeof val === 'object' && Array.isArray(val) === false
|
|
}
|
|
|
|
export function defaults(options, def) {
|
|
let out = { }
|
|
|
|
if (options) {
|
|
Object.keys(options || {}).forEach(key => {
|
|
out[key] = options[key]
|
|
|
|
if (Array.isArray(out[key])) {
|
|
out[key] = out[key].map(item => {
|
|
if (isObject(item)) return defaults(item)
|
|
return item
|
|
})
|
|
} else if (out[key] && typeof out[key] === 'object') {
|
|
out[key] = defaults(options[key], def && def[key])
|
|
}
|
|
})
|
|
}
|
|
|
|
if (def) {
|
|
Object.keys(def).forEach(function(key) {
|
|
if (typeof out[key] === 'undefined') {
|
|
out[key] = def[key]
|
|
}
|
|
})
|
|
}
|
|
|
|
return out
|
|
}
|