eltro/lib/sinon.mjs

68 lines
1.6 KiB
JavaScript

const indexMap = [
'firstCall',
'secondCall',
'thirdCall',
]
export function spy() {
return stub()
}
export function stub(returnFunc = null) {
if (returnFunc && typeof(returnFunc) !== 'function') {
throw new Error('stub() was called with non-function argument')
}
let returner = returnFunc ? returnFunc : null
let calls = []
let func = function(...args) {
func.called = true
calls.push(args)
func.lastCall = args
if (func.callCount < indexMap.length) {
func[indexMap[func.callCount]] = args
}
func.callCount++
if (returner) {
return returner(...args)
}
}
func.lastCall = null
func.called = false
func.callCount = 0
func.onCall = function(i) {
return calls[i]
}
func.reset = function() {
func.lastCall = null
func.called = false
func.callCount = 0
for (let i = 0; i < indexMap.length; i++) {
func[indexMap[i]] = null
}
returner = returnFunc ? returnFunc : null
calls.splice(0, calls.length)
}
func.returns = function(data) {
returner = function() { return data }
}
func.returnWith = function(returnFunc) {
if (typeof(returnFunc) !== 'function') {
throw new Error('stub() was called with non-function argument')
}
returner = returnFunc
}
func.throws = function(data) {
returner = function() { throw data }
}
func.resolves = function(data) {
returner = function() { return Promise.resolve(data) }
}
func.rejects = function(data) {
returner = function() { return Promise.reject(data) }
}
for (let i = 0; i < indexMap.length; i++) {
func[indexMap[i]] = null
}
return func
}