-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstubbing.js
More file actions
43 lines (37 loc) · 1.01 KB
/
stubbing.js
File metadata and controls
43 lines (37 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import sinon from 'sinon'
// /////////////////////////////////////////////////////////////////////////////
//
// Stubbing, the easy way
//
// /////////////////////////////////////////////////////////////////////////////
const stubs = new Map()
export const stub = (target, name, handler) => {
if (stubs.get(target)) {
throw new Error(`already stubbed: ${name}`)
}
const stubbedTarget = sinon.stub(target, name)
if (typeof handler === 'function') {
stubbedTarget.callsFake(handler)
} else {
stubbedTarget.value(handler)
}
stubs.set(stubbedTarget, name)
return stubbedTarget
}
export const restore = (target, name) => {
if (!target[name] || !target[name].restore) {
throw new Error(`not stubbed: ${name}`)
}
target[name].restore()
stubs.delete(target)
}
export const overrideStub = (target, name, handler) => {
restore(target, name)
stub(target, name, handler)
}
export const restoreAll = () => {
stubs.forEach((name, target) => {
target.restore()
stubs.delete(target)
})
}