-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest-helpers.tests.js
58 lines (47 loc) · 1.6 KB
/
test-helpers.tests.js
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import SimpleSchema from 'simpl-schema'
import { SchemaOptions } from './schema/SchemaOptions'
import sinon from 'sinon'
// allow our custom schema keys here to pass schema based tests
SimpleSchema.extendOptions(Object.keys(SchemaOptions))
export const createSchema = (schema, options) => new SimpleSchema(schema, options)
export const multiSchema = (...defs) => SimpleSchema.oneOf(defs)
export const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
export const iterate = (num, fct) => (new Array(num)).forEach(fct)
export const unsafeInt = negative => negative
? (Number.MIN_SAFE_INTEGER - 1)
: (Number.MAX_SAFE_INTEGER + 1)
// /////////////////////////////////////////////////////////////////////////////
//
// 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)
}
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)
})
}