UNPKG

1.98 kBJavaScriptView Raw
1import _ from './wrap/lodash'
2import log from './log'
3import tdFunction from './function'
4import imitate from './imitate'
5import proxy from './object/proxy'
6
7const DEFAULT_OPTIONS = { excludeMethods: ['then'] }
8
9export default function object (nameOrType, config) {
10 return _.tap(fakeObject(nameOrType, config, arguments.length), (obj) => {
11 addToStringToDouble(obj, nameOrType)
12 })
13}
14
15const fakeObject = function (nameOrType, config, argCount) {
16 if (_.isArray(nameOrType)) {
17 return createTestDoublesForFunctionNames(nameOrType)
18 } else if (_.isObjectLike(nameOrType)) {
19 return imitate(nameOrType)
20 } else if (_.isString(nameOrType) || argCount === 0) {
21 return proxy(nameOrType, withDefaults(config))
22 } else if (_.isFunction(nameOrType)) {
23 ensureFunctionIsNotPassed()
24 } else {
25 ensureOtherGarbageIsNotPassed()
26 }
27}
28
29const createTestDoublesForFunctionNames = (names) =>
30 _.transform(names, (acc, funcName) => {
31 acc[funcName] = tdFunction(`.${String(funcName)}`)
32 }, {})
33
34const ensureFunctionIsNotPassed = () =>
35 log.error('td.object', 'Functions are not valid arguments to `td.object` (as of testdouble@2.0.0). Please use `td.function()`, `td.constructor()` or `td.instance()` instead for creating fake functions.')
36
37const ensureOtherGarbageIsNotPassed = () =>
38 log.error('td.object', `\
39To create a fake object with td.object(), pass it a plain object that contains
40functions, an array of function names, or (if your runtime supports ES Proxy
41objects) a string name.
42
43If you passed td.object an instance of a custom type, consider passing the
44type's constructor to \`td.constructor()\` instead.
45`)
46
47const withDefaults = (config) =>
48 _.extend({}, DEFAULT_OPTIONS, config)
49
50const addToStringToDouble = (fakeObject, nameOrType) => {
51 const name = nameOf(nameOrType)
52 fakeObject.toString = () => `[test double object${name ? ` for "${name}"` : ''}]`
53}
54
55const nameOf = (nameOrType) =>
56 _.isString(nameOrType)
57 ? nameOrType
58 : ''