55 lines
1.3 KiB
JavaScript
55 lines
1.3 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)
|
|
if (func.callCount < indexMap.length) {
|
|
func[indexMap[func.callCount]] = args
|
|
}
|
|
func.callCount++
|
|
if (returner) {
|
|
return returner(...args)
|
|
}
|
|
}
|
|
func.called = false
|
|
func.callCount = 0
|
|
func.onCall = function(i) {
|
|
return calls[i]
|
|
}
|
|
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
|
|
}
|