2021-10-09 23:02:51 +00:00
|
|
|
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)
|
2021-10-10 03:24:41 +00:00
|
|
|
func.lastCall = args
|
2021-10-09 23:02:51 +00:00
|
|
|
if (func.callCount < indexMap.length) {
|
|
|
|
func[indexMap[func.callCount]] = args
|
|
|
|
}
|
|
|
|
func.callCount++
|
|
|
|
if (returner) {
|
|
|
|
return returner(...args)
|
|
|
|
}
|
|
|
|
}
|
2021-10-10 03:24:41 +00:00
|
|
|
func.lastCall = null
|
2021-10-09 23:02:51 +00:00
|
|
|
func.called = false
|
|
|
|
func.callCount = 0
|
|
|
|
func.onCall = function(i) {
|
|
|
|
return calls[i]
|
|
|
|
}
|
2021-10-09 23:20:01 +00:00
|
|
|
func.reset = function() {
|
2021-10-10 03:24:41 +00:00
|
|
|
func.lastCall = null
|
2021-10-09 23:20:01 +00:00
|
|
|
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)
|
|
|
|
}
|
2021-10-09 23:02:51 +00:00
|
|
|
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
|
|
|
|
}
|