-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathobject.js
83 lines (69 loc) · 2.6 KB
/
object.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import _ from './util/lodash-wrap'
import log from './log'
import tdFunction from './function'
import imitate from './imitate'
const DEFAULT_OPTIONS = {excludeMethods: ['then']}
export default (nameOrType, config) =>
_.tap(fakeObject(nameOrType, config), (obj) => {
addToStringToDouble(obj, nameOrType)
})
var fakeObject = (nameOrType, config) => {
if (_.isArray(nameOrType)) {
return createTestDoublesForFunctionNames(nameOrType)
} else if (_.isObjectLike(nameOrType)) {
return imitate(nameOrType)
} else if (_.isString(nameOrType) || nameOrType === undefined) {
return createTestDoubleViaProxy(nameOrType, withDefaults(config))
} else if (_.isFunction(nameOrType)) {
ensureFunctionIsNotPassed()
} else {
ensureOtherGarbageIsNotPassed()
}
}
var createTestDoublesForFunctionNames = (names) =>
_.transform(names, (acc, funcName) => {
acc[funcName] = tdFunction(`.${funcName}`)
})
var createTestDoubleViaProxy = (name, config) => {
ensureProxySupport(name)
const obj = {}
return new Proxy(obj, {
get (target, propKey, receiver) {
if (!obj.hasOwnProperty(propKey) && !_.includes(config.excludeMethods, propKey)) {
obj[propKey] = tdFunction(`${nameOf(name)}.${propKey}`)
}
return obj[propKey]
}
})
}
var ensureProxySupport = (name) => {
if (typeof Proxy === 'undefined') {
log.error('td.object', `\
The current runtime does not have Proxy support, which is what
testdouble.js depends on when a string name is passed to \`td.object()\`.
More details here:
https://github.com/testdouble/testdouble.js/blob/master/docs/4-creating-test-doubles.md#objectobjectname
Did you mean \`td.object(['${name}'])\`?\
`)
}
}
var ensureFunctionIsNotPassed = () =>
log.error('td.object', `Functions are not valid arguments to \`td.object\` (as of [email protected]). Please use \`td.function()\` or \`td.constructor()\` instead for creating fake functions.`)
var ensureOtherGarbageIsNotPassed = () =>
log.error('td.object', `\
To create a fake object with td.object(), pass it a plain object that contains
functions, an array of function names, or (if your runtime supports ES Proxy
objects) a string name.
If you passed td.object an instance of a custom type, consider passing the
type's constructor to \`td.constructor()\` instead.
`)
var withDefaults = (config) =>
_.extend({}, DEFAULT_OPTIONS, config)
var addToStringToDouble = (fakeObject, nameOrType) => {
const name = nameOf(nameOrType)
fakeObject.toString = () => `[test double object${name ? ` for "${name}"` : ''}]`
}
var nameOf = (nameOrType) =>
_.isString(nameOrType)
? nameOrType
: ''