UNPKG

1.73 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const theredoc = require("theredoc");
4const lodash_1 = require("../wrap/lodash");
5const log_1 = require("../log");
6const function_1 = require("../function");
7const store_1 = require("../store");
8function proxy(name, { excludeMethods } = {}) {
9 ensureProxySupport(name);
10 return new Proxy({}, generateHandler(name, excludeMethods));
11}
12exports.default = proxy;
13const ensureProxySupport = (name) => {
14 if (typeof Proxy === 'undefined') {
15 log_1.default.error('td.object', theredoc `\
16 The current runtime does not have Proxy support, which is what
17 testdouble.js depends on when a string name is passed to \`td.object()\`.
18
19 More details here:
20 https://github.com/testdouble/testdouble.js/blob/master/docs/4-creating-test-doubles.md#objectobjectname
21
22 Did you mean \`td.object(['${name}'])\`?
23 `);
24 }
25};
26const generateHandler = (internalName, excludeMethods) => ({
27 get(target, propKey) {
28 return generateGet(target, propKey, internalName, excludeMethods);
29 }
30});
31const generateGet = (target, propKey, internalName, excludeMethods) => {
32 if (propKey === Symbol('__is_proxy')) {
33 return true;
34 }
35 if (!Object.prototype.hasOwnProperty.call(target, propKey) &&
36 !lodash_1.default.includes(excludeMethods, propKey)) {
37 const nameWithProp = `${internalName || ''}.${String(propKey)}`;
38 const tdFunc = function_1.default(nameWithProp);
39 const tdFuncProxy = new Proxy(tdFunc, generateHandler(nameWithProp, excludeMethods));
40 store_1.default.registerAlias(tdFunc, tdFuncProxy);
41 target[propKey] = tdFuncProxy;
42 }
43 return target[propKey];
44};