flaska/test/helper.mjs

118 lines
2.2 KiB
JavaScript

const indexMap = [
'firstCall',
'secondCall',
'thirdCall',
]
export function spy() {
let calls = []
let called = 0
let func = function(...args) {
func.called = true
calls.push(args)
if (called < indexMap.length) {
func[indexMap[called]] = args
}
called++
func.callCount = called
}
func.called = false
func.callCount = called
func.onCall = function(i) {
return calls[i]
}
for (let i = 0; i < indexMap.length; i++) {
func[indexMap] = null
}
return func
}
export function fakeHttp(inj1, inj2) {
let intermediate = {
createServer: function(cb) {
if (inj1) inj1(cb)
intermediate.fakeRequest = cb
return {
listen: function(port, cb) {
if (inj2) inj2(port, cb)
else if (cb) cb()
}
}
}
}
return intermediate
}
export function createReq(def) {
return defaults(def, {
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) {
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,
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
}