1 | import _ from './wrap/lodash'
|
2 | import log from './log'
|
3 | import tdFunction from './function'
|
4 | import imitate from './imitate'
|
5 | import proxy from './object/proxy'
|
6 |
|
7 | const DEFAULT_OPTIONS = { excludeMethods: ['then'] }
|
8 |
|
9 | export default function object (nameOrType, config) {
|
10 | return _.tap(fakeObject(nameOrType, config, arguments.length), (obj) => {
|
11 | addToStringToDouble(obj, nameOrType)
|
12 | })
|
13 | }
|
14 |
|
15 | const 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 |
|
29 | const createTestDoublesForFunctionNames = (names) =>
|
30 | _.transform(names, (acc, funcName) => {
|
31 | acc[funcName] = tdFunction(`.${String(funcName)}`)
|
32 | }, {})
|
33 |
|
34 | const 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 |
|
37 | const ensureOtherGarbageIsNotPassed = () =>
|
38 | log.error('td.object', `\
|
39 | To create a fake object with td.object(), pass it a plain object that contains
|
40 | functions, an array of function names, or (if your runtime supports ES Proxy
|
41 | objects) a string name.
|
42 |
|
43 | If you passed td.object an instance of a custom type, consider passing the
|
44 | type's constructor to \`td.constructor()\` instead.
|
45 | `)
|
46 |
|
47 | const withDefaults = (config) =>
|
48 | _.extend({}, DEFAULT_OPTIONS, config)
|
49 |
|
50 | const addToStringToDouble = (fakeObject, nameOrType) => {
|
51 | const name = nameOf(nameOrType)
|
52 | fakeObject.toString = () => `[test double object${name ? ` for "${name}"` : ''}]`
|
53 | }
|
54 |
|
55 | const nameOf = (nameOrType) =>
|
56 | _.isString(nameOrType)
|
57 | ? nameOrType
|
58 | : ''
|