Debian Codegraph @

debian/tests/test_modules/nanospy/index.js

raw symbols SCIP
1 let spies = []
2
3 function spy(cb) {
4 let fn = (...args) => {
5 fn.called = true
6 fn.callCount += 1
7 fn.calls.push(args)
8 if (fn.next) {
9 let [nextType, nextResult] = fn.next
10 fn.next = false
11 if (nextType === 'error') {
12 fn.results.push(undefined)
13 throw nextResult
14 } else {
15 fn.results.push(nextResult)
16 return nextResult
17 }
18 } else {
19 let result
20 if (fn.impl) result = fn.impl(...args)
21 fn.results.push(result)
22 return result
23 }
24 }
25
26 fn.called = false
27 fn.callCount = 0
28 fn.results = []
29 fn.calls = []
30 fn.nextError = error => {
31 fn.next = ['error', error]
32 }
33 fn.nextResult = result => {
34 fn.next = ['ok', result]
35 }
36 fn.onCall = body => {
37 Object.defineProperty(fn, 'length', { value: body ? body.length : 0 })
38 fn.impl = body
39 }
40 fn.onCall(cb)
41
42 return fn
43 }
44
45 function spyOn(obj, methodName, mock) {
46 let origin = obj[methodName]
47 if (!mock) mock = origin
48 let fn = spy(mock.bind(obj))
49 fn.restore = () => {
50 obj[methodName] = origin
51 }
52
53 obj[methodName] = fn
54
55 spies.push(fn)
56 return fn
57 }
58
59 function restoreAll() {
60 for (let fn of spies) {
61 fn.restore()
62 }
63 spies = []
64 }
65
66 module.exports.spy = spy
67 module.exports.spyOn = spyOn
68 module.exports.restoreAll = restoreAll