New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

testdouble

Package Overview
Dependencies
Maintainers
2
Versions
115
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

testdouble - npm Package Compare versions

Comparing version 3.14.0 to 3.15.0

lib/index.mjs

22

index.d.ts

@@ -264,2 +264,24 @@ //

export function replace(path: string, f?: any): any;
/**
* Swap out real dependenencies with fake one. Intercept calls to `require`
* that dependency module and ensure your subject is handed a fake instead.
*
* @export
* @param {string} path
* @param {*} [f]
* @returns {*}
*/
export function replaceCjs(path: string, f?: any): any;
/**
* Swap out real dependenencies with fake one. Intercept calls to `import`
* that dependency module and ensure your subject is handed a fake instead.
*
* @export
* @param {string} path
* @param {*} [namedExportStubs]
* @param {*} [defaultExportStub]
* @returns {Promise<{default?: any, [namedExport: string]: any}>}
*/
export function replaceEsm(path: string, namedExportStubs?: any, defaultExportStub?: any):
Promise<{default?: any, [namedExport: string]: any}>;

@@ -266,0 +288,0 @@ /**

25

lib/args-match.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var is_matcher_1 = require("./matchers/is-matcher");
exports.default = (function (expectedArgs, actualArgs, config) {
if (config === void 0) { config = {}; }
const lodash_1 = require("./wrap/lodash");
const is_matcher_1 = require("./matchers/is-matcher");
exports.default = (expectedArgs, actualArgs, config = {}) => {
if (arityMismatch(expectedArgs, actualArgs, config)) {

@@ -16,12 +15,6 @@ return false;

}
});
var arityMismatch = function (expectedArgs, actualArgs, config) {
return expectedArgs.length !== actualArgs.length && !config.ignoreExtraArgs;
};
var equalsWithMatchers = function (expectedArgs, actualArgs) {
return lodash_1.default.every(expectedArgs, function (expectedArg, key) {
return argumentMatchesExpectation(expectedArg, actualArgs[key]);
});
};
var argumentMatchesExpectation = function (expectedArg, actualArg) {
var arityMismatch = (expectedArgs, actualArgs, config) => expectedArgs.length !== actualArgs.length && !config.ignoreExtraArgs;
var equalsWithMatchers = (expectedArgs, actualArgs) => lodash_1.default.every(expectedArgs, (expectedArg, key) => argumentMatchesExpectation(expectedArg, actualArgs[key]));
var argumentMatchesExpectation = (expectedArg, actualArg) => {
if (is_matcher_1.default(expectedArg)) {

@@ -31,3 +24,3 @@ return matcherTestFor(expectedArg)(actualArg);

else {
return lodash_1.default.isEqualWith(expectedArg, actualArg, function (expectedEl, actualEl) {
return lodash_1.default.isEqualWith(expectedArg, actualArg, (expectedEl, actualEl) => {
if (is_matcher_1.default(expectedEl)) {

@@ -39,4 +32,2 @@ return matcherTestFor(expectedEl)(actualEl);

};
var matcherTestFor = function (matcher) {
return matcher.__matches;
};
var matcherTestFor = (matcher) => matcher.__matches;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var create_1 = require("./matchers/create");
var callback = create_1.default({
const lodash_1 = require("./wrap/lodash");
const create_1 = require("./matchers/create");
const callback = create_1.default({
name: 'callback',
matches: function (matcherArgs, actual) {
matches(matcherArgs, actual) {
return lodash_1.default.isFunction(actual);
},
onCreate: function (matcherInstance, matcherArgs) {
onCreate(matcherInstance, matcherArgs) {
matcherInstance.args = matcherArgs;

@@ -12,0 +12,0 @@ matcherInstance.__testdouble_callback = true;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var log_1 = require("./log");
var anything_1 = require("./stringify/anything");
var DEFAULTS = {
const lodash_1 = require("./wrap/lodash");
const log_1 = require("./log");
const anything_1 = require("./stringify/anything");
const DEFAULTS = {
ignoreWarnings: false,

@@ -11,17 +11,17 @@ promiseConstructor: global.Promise,

};
var DELETED_OPTIONS = ['extendWhenReplacingConstructors'];
var configData = lodash_1.default.extend({}, DEFAULTS);
exports.default = lodash_1.default.tap(function (overrides) {
const DELETED_OPTIONS = ['extendWhenReplacingConstructors'];
let configData = lodash_1.default.extend({}, DEFAULTS);
exports.default = lodash_1.default.tap((overrides) => {
deleteDeletedOptions(overrides);
ensureOverridesExist(overrides);
return lodash_1.default.extend(configData, overrides);
}, function (config) {
config.reset = function () {
}, (config) => {
config.reset = () => {
configData = lodash_1.default.extend({}, DEFAULTS);
};
});
var deleteDeletedOptions = function (overrides) {
lodash_1.default.each(overrides, function (val, key) {
const deleteDeletedOptions = (overrides) => {
lodash_1.default.each(overrides, (val, key) => {
if (lodash_1.default.includes(DELETED_OPTIONS, key)) {
log_1.default.warn('td.config', "\"" + key + "\" is no longer a valid configuration key. Remove it from your calls to td.config() or it may throw an error in the future. For more information, try hunting around our GitHub repo for it:\n\n https://github.com/testdouble/testdouble.js/search?q=" + key);
log_1.default.warn('td.config', `"${key}" is no longer a valid configuration key. Remove it from your calls to td.config() or it may throw an error in the future. For more information, try hunting around our GitHub repo for it:\n\n https://github.com/testdouble/testdouble.js/search?q=${key}`);
delete overrides[key];

@@ -31,8 +31,8 @@ }

};
var ensureOverridesExist = function (overrides) {
lodash_1.default.each(overrides, function (val, key) {
var ensureOverridesExist = (overrides) => {
lodash_1.default.each(overrides, (val, key) => {
if (!Object.prototype.hasOwnProperty.call(configData, key)) {
log_1.default.error('td.config', "\"" + key + "\" is not a valid configuration key (valid keys are: " + anything_1.default(lodash_1.default.keys(configData)) + ")");
log_1.default.error('td.config', `"${key}" is not a valid configuration key (valid keys are: ${anything_1.default(lodash_1.default.keys(configData))})`);
}
});
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var function_1 = require("./function");
var imitate_1 = require("./imitate");
exports.default = (function (typeOrNames) {
return lodash_1.default.isFunction(typeOrNames)
? imitate_1.default(typeOrNames)
: fakeConstructorFromNames(typeOrNames);
});
var fakeConstructorFromNames = function (funcNames) {
return lodash_1.default.tap(function_1.default('(unnamed constructor)'), function (fakeConstructor) {
fakeConstructor.prototype.toString = function () {
return '[test double instance of constructor]';
};
lodash_1.default.each(funcNames, function (funcName) {
fakeConstructor.prototype[funcName] = function_1.default("#" + String(funcName));
const lodash_1 = require("./wrap/lodash");
const function_1 = require("./function");
const imitate_1 = require("./imitate");
exports.default = (typeOrNames) => lodash_1.default.isFunction(typeOrNames)
? imitate_1.default(typeOrNames)
: fakeConstructorFromNames(typeOrNames);
var fakeConstructorFromNames = (funcNames) => {
return lodash_1.default.tap(function_1.default('(unnamed constructor)'), (fakeConstructor) => {
fakeConstructor.prototype.toString = () => '[test double instance of constructor]';
lodash_1.default.each(funcNames, (funcName) => {
fakeConstructor.prototype[funcName] = function_1.default(`#${String(funcName)}`);
});
});
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var proxy_safe_clone_deep_with_1 = require("./wrap/proxy-safe-clone-deep-with");
var calls_1 = require("./store/calls");
var store_1 = require("./store");
var arguments_1 = require("./stringify/arguments");
var stubbings_1 = require("./store/stubbings");
const lodash_1 = require("./wrap/lodash");
const proxy_safe_clone_deep_with_1 = require("./wrap/proxy-safe-clone-deep-with");
const calls_1 = require("./store/calls");
const store_1 = require("./store");
const arguments_1 = require("./stringify/arguments");
const stubbings_1 = require("./store/stubbings");
function explain(testDouble) {

@@ -22,3 +22,3 @@ if (lodash_1.default.isFunction(testDouble)) {

function explainObject(obj) {
var _a = explainChildren(obj), explanations = _a.explanations, children = _a.children;
const { explanations, children } = explainChildren(obj);
return {

@@ -29,3 +29,3 @@ name: null,

description: describeObject(explanations),
children: children,
children,
isTestDouble: explanations.length > 0

@@ -35,6 +35,6 @@ };

function explainChildren(thing) {
var explanations = [];
var children = proxy_safe_clone_deep_with_1.default(thing, function (val, key, obj, stack) {
const explanations = [];
const children = proxy_safe_clone_deep_with_1.default(thing, (val, key, obj, stack) => {
if (lodash_1.default.isFunction(val) && stack) {
return lodash_1.default.tap(explainFunction(val), function (explanation) {
return lodash_1.default.tap(explainFunction(val), (explanation) => {
if (explanation.isTestDouble)

@@ -45,11 +45,9 @@ explanations.push(explanation);

});
return { explanations: explanations, children: children };
return { explanations, children };
}
function describeObject(explanations) {
var count = explanations.length;
const count = explanations.length;
if (count === 0)
return 'This object contains no test doubles';
return "This object contains " + count + " test double function" + (count > 1 ? 's' : '') + ": [" + lodash_1.default.map(explanations, function (e) {
return "\"" + e.name + "\"";
}).join(', ') + "]";
return `This object contains ${count} test double function${count > 1 ? 's' : ''}: [${lodash_1.default.map(explanations, e => `"${e.name}"`).join(', ')}]`;
}

@@ -60,13 +58,13 @@ function explainFunction(testDouble) {

}
var calls = calls_1.default.for(testDouble);
var stubs = stubbings_1.default.for(testDouble);
var children = explainChildren(testDouble).children;
const calls = calls_1.default.for(testDouble);
const stubs = stubbings_1.default.for(testDouble);
const { children } = explainChildren(testDouble);
return {
name: store_1.default.for(testDouble).name,
callCount: calls.length,
calls: calls,
calls,
description: testdoubleDescription(testDouble, stubs, calls) +
stubbingDescription(stubs) +
callDescription(calls),
children: children,
children,
isTestDouble: true

@@ -80,3 +78,3 @@ };

calls: [],
description: "This is not a test double" + (lodash_1.default.isFunction(thing) ? ' function' : '') + ".",
description: `This is not a test double${lodash_1.default.isFunction(thing) ? ' function' : ''}.`,
isTestDouble: false

@@ -86,9 +84,7 @@ });

function testdoubleDescription(testDouble, stubs, calls) {
return "This test double " + stringifyName(testDouble) + "has " + stubs.length + " stubbings and " + calls.length + " invocations.";
return `This test double ${stringifyName(testDouble)}has ${stubs.length} stubbings and ${calls.length} invocations.`;
}
function stubbingDescription(stubs) {
return stubs.length > 0
? lodash_1.default.reduce(stubs, function (desc, stub) {
return desc + ("\n - when called with `(" + arguments_1.default(stub.args) + ")`, then " + planFor(stub) + " " + argsFor(stub) + ".");
}, '\n\nStubbings:')
? lodash_1.default.reduce(stubs, (desc, stub) => desc + `\n - when called with \`(${arguments_1.default(stub.args)})\`, then ${planFor(stub)} ${argsFor(stub)}.`, '\n\nStubbings:')
: '';

@@ -106,3 +102,3 @@ }

switch (stub.config.plan) {
case 'thenCallback': return "`(" + arguments_1.default(stub.stubbedValues, ', ') + ")`";
case 'thenCallback': return `\`(${arguments_1.default(stub.stubbedValues, ', ')})\``;
default: return arguments_1.default(stub.stubbedValues, ', then ', '`');

@@ -113,8 +109,8 @@ }

return calls.length > 0
? lodash_1.default.reduce(calls, function (desc, call) { return desc + ("\n - called with `(" + arguments_1.default(call.cloneArgs) + ")`."); }, '\n\nInvocations:')
? lodash_1.default.reduce(calls, (desc, call) => desc + `\n - called with \`(${arguments_1.default(call.cloneArgs)})\`.`, '\n\nInvocations:')
: '';
}
function stringifyName(testDouble) {
var name = store_1.default.for(testDouble).name;
return name ? "`" + name + "` " : '';
const name = store_1.default.for(testDouble).name;
return name ? `\`${name}\` ` : '';
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var calls_1 = require("./store/calls");
var store_1 = require("./store");
var stubbings_1 = require("./store/stubbings");
var imitate_1 = require("./imitate");
const lodash_1 = require("./wrap/lodash");
const calls_1 = require("./store/calls");
const store_1 = require("./store");
const stubbings_1 = require("./store/stubbings");
const imitate_1 = require("./imitate");
function func(nameOrFunc, __optionalName) {

@@ -15,10 +15,10 @@ return lodash_1.default.isFunction(nameOrFunc)

var createTestDoubleNamed = function (name) {
return lodash_1.default.tap(createTestDoubleFunction(), function (testDouble) {
var entry = store_1.default.for(testDouble, true);
return lodash_1.default.tap(createTestDoubleFunction(), (testDouble) => {
const entry = store_1.default.for(testDouble, true);
if (name != null) {
entry.name = name;
testDouble.toString = function () { return "[test double for \"" + name + "\"]"; };
testDouble.toString = () => `[test double for "${name}"]`;
}
else {
testDouble.toString = function () { return '[test double (unnamed)]'; };
testDouble.toString = () => '[test double (unnamed)]';
}

@@ -28,7 +28,3 @@ });

var createTestDoubleFunction = function () {
return function testDouble() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return function testDouble(...args) {
calls_1.default.log(testDouble, args, this);

@@ -35,0 +31,0 @@ return stubbings_1.default.invoke(testDouble, args, this);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var double_1 = require("../value/double");
var generate_fake_function_1 = require("./generate-fake-function");
const double_1 = require("../value/double");
const generate_fake_function_1 = require("./generate-fake-function");
function create(name, real, parent) {

@@ -6,0 +6,0 @@ return double_1.default.create(name, real, parent, generate_fake_function_1.default);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var call_log_1 = require("../value/call-log");
var call_1 = require("../value/call");
var satisfy_1 = require("../satisfy");
const call_log_1 = require("../value/call-log");
const call_1 = require("../value/call");
const satisfy_1 = require("../satisfy");
function generateFakeFunction(double) {
var testDouble = function testDouble() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var call = new call_1.default(this, args);
const testDouble = function testDouble(...args) {
const call = new call_1.default(this, args);
call_log_1.default.instance.log(double, call);

@@ -14,0 +10,0 @@ return satisfy_1.default(double, call);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var create_1 = require("./create");
const lodash_1 = require("../wrap/lodash");
const create_1 = require("./create");
function func(nameOrFunc) {

@@ -6,0 +6,0 @@ if (lodash_1.default.isFunction(nameOrFunc)) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var function_1 = require("../function");
var is_generator_1 = require("./is-generator");
exports.default = (function (original, names) {
const lodash_1 = require("../wrap/lodash");
const function_1 = require("../function");
const is_generator_1 = require("./is-generator");
exports.default = (original, names) => {
if (lodash_1.default.isArray(original) || lodash_1.default.isArguments(original)) {

@@ -22,2 +22,2 @@ return [];

}
});
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var initialize_names_1 = require("./initialize-names");
var create_imitation_1 = require("./create-imitation");
var overwrite_children_1 = require("./overwrite-children");
function imitate(original, names, encounteredObjects) {
if (encounteredObjects === void 0) { encounteredObjects = new Map(); }
const initialize_names_1 = require("./initialize-names");
const create_imitation_1 = require("./create-imitation");
const overwrite_children_1 = require("./overwrite-children");
function imitate(original, names, encounteredObjects = new Map()) {
if (encounteredObjects.has(original))
return encounteredObjects.get(original);
names = initialize_names_1.default(original, names);
var target = create_imitation_1.default(original, names);
const target = create_imitation_1.default(original, names);
encounteredObjects.set(original, target);
overwrite_children_1.default(original, target, function (originalValue, name) {
return imitate(originalValue, names.concat(name), encounteredObjects);
});
overwrite_children_1.default(original, target, (originalValue, name) => imitate(originalValue, names.concat(name), encounteredObjects));
return target;
}
exports.default = imitate;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
exports.default = (function (original, names) {
const lodash_1 = require("../wrap/lodash");
exports.default = (original, names) => {
if (lodash_1.default.isString(names))

@@ -15,2 +15,2 @@ return [names];

}
});
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var generatorsAreSupported = (function () {
const generatorsAreSupported = (function () {
try {

@@ -12,10 +12,8 @@ eval('(function* () {})'); // eslint-disable-line

})();
var GeneratorFunction = (function () {
const GeneratorFunction = (function () {
if (!generatorsAreSupported)
return;
var func = eval('(function* () {})'); // eslint-disable-line
const func = eval('(function* () {})'); // eslint-disable-line
return Object.getPrototypeOf(func).constructor;
})();
exports.default = (function (func) {
return generatorsAreSupported && func.constructor === GeneratorFunction;
});
exports.default = (func) => generatorsAreSupported && func.constructor === GeneratorFunction;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
exports.default = (function (original, target, name, originalValue, targetValue) {
const lodash_1 = require("../../wrap/lodash");
exports.default = (original, target, name, originalValue, targetValue) => {
if (name !== 'prototype' || !lodash_1.default.isFunction(original))

@@ -10,2 +10,2 @@ return targetValue;

return targetValue;
});
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
exports.default = (function (target, props, visitor) {
Object.defineProperties(target, lodash_1.default.transform(props, function (acc, descriptor, name) {
const lodash_1 = require("../../wrap/lodash");
exports.default = (target, props, visitor) => {
Object.defineProperties(target, lodash_1.default.transform(props, (acc, descriptor, name) => {
if (propOnTargetAndNotWritable(target, name, descriptor)) {

@@ -21,5 +21,5 @@ if (name === 'prototype') {

}));
});
var propOnTargetAndNotWritable = function (target, name, originalDescriptor) {
var targetDescriptor = Object.getOwnPropertyDescriptor(target, name);
};
const propOnTargetAndNotWritable = (target, name, originalDescriptor) => {
const targetDescriptor = Object.getOwnPropertyDescriptor(target, name);
if (targetDescriptor &&

@@ -30,4 +30,4 @@ (!targetDescriptor.writable || !targetDescriptor.configurable)) {

};
var newValue = function (name, value, visitor) {
const newValue = (name, value, visitor) => {
return visitor ? visitor(name, value) : value;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var is_fakeable_1 = require("./is-fakeable");
var is_native_prototype_1 = require("./is-native-prototype");
const is_fakeable_1 = require("./is-fakeable");
const is_native_prototype_1 = require("./is-native-prototype");
function gatherProps(thing) {
var props = {};
const props = {};
while (is_fakeable_1.default(thing) && !is_native_prototype_1.default(thing)) {
Object.getOwnPropertyNames(thing).forEach(function (propName) {
Object.getOwnPropertyNames(thing).forEach((propName) => {
if (!props[propName] && propName !== 'constructor') {

@@ -10,0 +10,0 @@ props[propName] = Object.getOwnPropertyDescriptor(thing, propName);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
var is_fakeable_1 = require("./is-fakeable");
var gather_props_1 = require("./gather-props");
var copy_props_1 = require("./copy-props");
var chain_prototype_1 = require("./chain-prototype");
exports.default = (function (original, target, overwriteChild) {
const lodash_1 = require("../../wrap/lodash");
const is_fakeable_1 = require("./is-fakeable");
const gather_props_1 = require("./gather-props");
const copy_props_1 = require("./copy-props");
const chain_prototype_1 = require("./chain-prototype");
exports.default = (original, target, overwriteChild) => {
if (!is_fakeable_1.default(target))
return;
if (lodash_1.default.isArray(target)) {
lodash_1.default.each(original, function (item, index) {
return target.push(overwriteChild(item, "[" + index + "]"));
});
lodash_1.default.each(original, (item, index) => target.push(overwriteChild(item, `[${index}]`)));
}
else {
copy_props_1.default(target, gather_props_1.default(original), function (name, originalValue) {
return chain_prototype_1.default(original, target, name, originalValue, overwriteChild(originalValue, "." + name));
});
copy_props_1.default(target, gather_props_1.default(original), (name, originalValue) => chain_prototype_1.default(original, target, name, originalValue, overwriteChild(originalValue, `.${name}`)));
}
});
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
var is_generator_1 = require("../is-generator");
exports.default = (function (thing) {
return !(!lodash_1.default.isObject(thing) || isBoxedType(thing) || is_generator_1.default(thing));
});
var isBoxedType = function (thing) {
return lodash_1.default.compact([
Boolean,
Date,
Number,
RegExp,
String,
global.Symbol
]).some(function (type) { return thing instanceof type; });
};
const lodash_1 = require("../../wrap/lodash");
const is_generator_1 = require("../is-generator");
exports.default = (thing) => !(!lodash_1.default.isObject(thing) || isBoxedType(thing) || is_generator_1.default(thing));
const isBoxedType = (thing) => lodash_1.default.compact([
Boolean,
Date,
Number,
RegExp,
String,
global.Symbol
]).some(type => thing instanceof type);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
const lodash_1 = require("../../wrap/lodash");
function isNativePrototype(thing) {
if (thing == null || !lodash_1.default.isFunction(thing.isPrototypeOf))
return false;
return lodash_1.default.some([Object, Function], function (nativeType) {
return Object.prototype.isPrototypeOf.call(thing, nativeType);
});
return lodash_1.default.some([Object, Function], (nativeType) => Object.prototype.isPrototypeOf.call(thing, nativeType));
}
exports.default = isNativePrototype;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var function_1 = require("./function");
var object_1 = require("./object");
var constructor_1 = require("./constructor");
var imitate_1 = require("./imitate");
var when_1 = require("./when");
var verify_1 = require("./verify");
var matchers_1 = require("./matchers");
var replace_1 = require("./replace");
var explain_1 = require("./explain");
var reset_1 = require("./reset");
var config_1 = require("./config");
var callback_1 = require("./callback");
var version_1 = require("./version");
var quibble = require("quibble");
const function_1 = require("./function");
const object_1 = require("./object");
const constructor_1 = require("./constructor");
const imitate_1 = require("./imitate");
const when_1 = require("./when");
const verify_1 = require("./verify");
const matchers_1 = require("./matchers");
const replace_1 = require("./replace");
const explain_1 = require("./explain");
const reset_1 = require("./reset");
const config_1 = require("./config");
const callback_1 = require("./callback");
const version_1 = require("./version");
const quibble = require("quibble");
module.exports = {

@@ -27,2 +27,3 @@ function: function_1.default,

replace: replace_1.default,
replaceEsm: replace_1.replaceEsm,
explain: explain_1.default,

@@ -33,3 +34,3 @@ reset: reset_1.default,

version: version_1.default,
quibble: quibble
quibble
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var config_1 = require("./config");
const config_1 = require("./config");
exports.default = {
warn: function (func, msg, url) {
warn(func, msg, url) {
if (!config_1.default().ignoreWarnings && typeof console === 'object' && console.warn) {
console.warn("Warning: testdouble.js - " + func + " - " + msg + withUrl(url));
console.warn(`Warning: testdouble.js - ${func} - ${msg}${withUrl(url)}`);
}
},
error: function (func, msg, url) {
error(func, msg, url) {
if (!config_1.default().suppressErrors) {
throw new Error("Error: testdouble.js - " + func + " - " + msg + withUrl(url));
throw new Error(`Error: testdouble.js - ${func} - ${msg}${withUrl(url)}`);
}
},
fail: function (msg) {
fail(msg) {
throw new Error(msg);
}
};
var withUrl = function (url) {
return url != null
? " (see: " + url + " )"
: '';
};
var withUrl = (url) => url != null
? ` (see: ${url} )`
: '';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var config_1 = require("../config");
var log_1 = require("../log");
var MESSAGES = {
warn: "no promise constructor is set, so this `thenResolve` or `thenReject` stubbing\nwill fail if it's satisfied by an invocation on the test double. You can tell\ntestdouble.js which promise constructor to use with `td.config`, like so:",
error: "no promise constructor is set (perhaps this runtime lacks a native Promise\nfunction?), which means this stubbing can't return a promise to your\nsubject under test, resulting in this error. To resolve the issue, set\na promise constructor with `td.config`, like this:"
const config_1 = require("../config");
const log_1 = require("../log");
const MESSAGES = {
warn: `\
no promise constructor is set, so this \`thenResolve\` or \`thenReject\` stubbing
will fail if it's satisfied by an invocation on the test double. You can tell
testdouble.js which promise constructor to use with \`td.config\`, like so:`,
error: `\
no promise constructor is set (perhaps this runtime lacks a native Promise
function?), which means this stubbing can't return a promise to your
subject under test, resulting in this error. To resolve the issue, set
a promise constructor with \`td.config\`, like this:`
};
function ensurePromise(level) {
if (config_1.default().promiseConstructor == null) {
log_1.default[level]('td.when', MESSAGES[level] + "\n\n td.config({\n promiseConstructor: require('bluebird')\n })");
log_1.default[level]('td.when', `\
${MESSAGES[level]}
td.config({
promiseConstructor: require('bluebird')
})\
`);
}
}
exports.default = ensurePromise;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var create_1 = require("../create");
const create_1 = require("../create");
exports.default = create_1.default({
name: 'anything',
matches: function () { return true; }
matches() { return true; }
});
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var create_1 = require("../create");
const create_1 = require("../create");
exports.default = create_1.default({
name: 'argThat',
matches: function (matcherArgs, actual) {
var predicate = matcherArgs[0];
matches(matcherArgs, actual) {
const predicate = matcherArgs[0];
return predicate(actual);
}
});
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var create_1 = require("../create");
exports.default = (function () {
var captor = {
const create_1 = require("../create");
exports.default = () => {
const captor = {
capture: create_1.default({
name: 'captor.capture',
matches: function (matcherArgs, actual) {
matches(matcherArgs, actual) {
return true;
},
afterSatisfaction: function (matcherArgs, actual) {
afterSatisfaction(matcherArgs, actual) {
captor.values = captor.values || [];

@@ -19,2 +19,2 @@ captor.values.push(actual);

return captor;
});
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
var create_1 = require("../create");
var is_matcher_1 = require("../is-matcher");
const lodash_1 = require("../../wrap/lodash");
const create_1 = require("../create");
const is_matcher_1 = require("../is-matcher");
exports.default = create_1.default({
name: 'contains',
matches: function (containings, actualArg) {
matches(containings, actualArg) {
if (containings.length === 0)
return false;
return lodash_1.default.every(containings, function (containing) {
return argumentContains(containing, actualArg);
});
return lodash_1.default.every(containings, (containing) => argumentContains(containing, actualArg));
}
});
var argumentContains = function (containing, actualArg) {
const argumentContains = function (containing, actualArg) {
if (lodash_1.default.isArray(containing)) {
return lodash_1.default.some(actualArg, function (actualElement) {
return lodash_1.default.isEqualWith(containing, actualElement, equalish);
});
return lodash_1.default.some(actualArg, actualElement => lodash_1.default.isEqualWith(containing, actualElement, equalish));
}

@@ -26,3 +22,3 @@ else {

};
var equalish = function (containing, actualArg) {
const equalish = function (containing, actualArg) {
if (lodash_1.default.isRegExp(containing)) {

@@ -61,6 +57,4 @@ if (lodash_1.default.isString(actualArg)) {

};
var containsPartialObject = function (containing, actual) {
return lodash_1.default.every(containing, function (val, key) {
return lodash_1.default.isEqualWith(val, actual[key], equalish);
});
const containsPartialObject = (containing, actual) => {
return lodash_1.default.every(containing, (val, key) => lodash_1.default.isEqualWith(val, actual[key], equalish));
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
var create_1 = require("../create");
var arguments_1 = require("../../stringify/arguments");
const lodash_1 = require("../../wrap/lodash");
const create_1 = require("../create");
const arguments_1 = require("../../stringify/arguments");
exports.default = create_1.default({
name: function (matcherArgs) {
var desc = lodash_1.default.get(matcherArgs[0], 'name') || arguments_1.default(matcherArgs);
return "isA(" + desc + ")";
name(matcherArgs) {
const desc = lodash_1.default.get(matcherArgs[0], 'name') || arguments_1.default(matcherArgs);
return `isA(${desc})`;
},
matches: function (matcherArgs, actual) {
var type = matcherArgs[0];
matches(matcherArgs, actual) {
const type = matcherArgs[0];
if (type === Number) {

@@ -14,0 +14,0 @@ return lodash_1.default.isNumber(actual);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
var create_1 = require("../create");
const lodash_1 = require("../../wrap/lodash");
const create_1 = require("../create");
exports.default = create_1.default({
name: 'not',
matches: function (matcherArgs, actual) {
var expected = matcherArgs[0];
matches(matcherArgs, actual) {
const expected = matcherArgs[0];
return !lodash_1.default.isEqual(expected, actual);
}
});
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var arguments_1 = require("../stringify/arguments");
exports.default = (function (config) {
return function () {
var matcherArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
matcherArgs[_i] = arguments[_i];
}
return lodash_1.default.tap({
__name: nameFor(config, matcherArgs),
__matches: function (actualArg) {
return config.matches(matcherArgs, actualArg);
}
}, function (matcherInstance) {
matcherInstance.__matches.afterSatisfaction = function (actualArg) {
lodash_1.default.invoke(config, 'afterSatisfaction', matcherArgs, actualArg);
};
lodash_1.default.invoke(config, 'onCreate', matcherInstance, matcherArgs);
});
const lodash_1 = require("../wrap/lodash");
const arguments_1 = require("../stringify/arguments");
exports.default = config => (...matcherArgs) => lodash_1.default.tap({
__name: nameFor(config, matcherArgs),
__matches(actualArg) {
return config.matches(matcherArgs, actualArg);
}
}, (matcherInstance) => {
matcherInstance.__matches.afterSatisfaction = (actualArg) => {
lodash_1.default.invoke(config, 'afterSatisfaction', matcherArgs, actualArg);
};
lodash_1.default.invoke(config, 'onCreate', matcherInstance, matcherArgs);
});
var nameFor = function (config, matcherArgs) {
var nameFor = (config, matcherArgs) => {
if (lodash_1.default.isFunction(config.name)) {

@@ -29,7 +21,7 @@ return config.name(matcherArgs);

else if (config.name != null) {
return config.name + "(" + arguments_1.default(matcherArgs) + ")";
return `${config.name}(${arguments_1.default(matcherArgs)})`;
}
else {
return "[Matcher for (" + arguments_1.default(matcherArgs) + ")]";
return `[Matcher for (${arguments_1.default(matcherArgs)})]`;
}
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var create_1 = require("./create");
var captor_1 = require("./builtin/captor");
var is_a_1 = require("./builtin/is-a");
var contains_1 = require("./builtin/contains");
var anything_1 = require("./builtin/anything");
var arg_that_1 = require("./builtin/arg-that");
var not_1 = require("./builtin/not");
const create_1 = require("./create");
const captor_1 = require("./builtin/captor");
const is_a_1 = require("./builtin/is-a");
const contains_1 = require("./builtin/contains");
const anything_1 = require("./builtin/anything");
const arg_that_1 = require("./builtin/arg-that");
const not_1 = require("./builtin/not");
exports.default = {

@@ -11,0 +11,0 @@ create: create_1.default,

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var callback_1 = require("../callback");
const callback_1 = require("../callback");
function isCallback(obj) {

@@ -5,0 +5,0 @@ return obj && (obj === callback_1.default || obj.__testdouble_callback === true);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (function (thing) {
return thing && !thing[Symbol('__is_proxy')] && thing.__matches;
});
exports.default = (thing) => thing && !thing[Symbol('__is_proxy')] && thing.__matches;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var is_matcher_1 = require("./is-matcher");
const lodash_1 = require("../wrap/lodash");
const is_matcher_1 = require("./is-matcher");
// TODO: after rewrite, update signature to take (Stubbing/Verification, Call)
function notifyAfterSatisfaction(expectedArgs, actualArgs) {
lodash_1.default.each(expectedArgs, function (expectedArg, i) {
lodash_1.default.each(expectedArgs, (expectedArg, i) => {
if (is_matcher_1.default(expectedArg)) {

@@ -9,0 +9,0 @@ lodash_1.default.invoke(expectedArg, '__matches.afterSatisfaction', actualArgs[i]);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var log_1 = require("./log");
var function_1 = require("./function");
var imitate_1 = require("./imitate");
var proxy_1 = require("./object/proxy");
var DEFAULT_OPTIONS = { excludeMethods: ['then'] };
const lodash_1 = require("./wrap/lodash");
const log_1 = require("./log");
const function_1 = require("./function");
const imitate_1 = require("./imitate");
const proxy_1 = require("./object/proxy");
const DEFAULT_OPTIONS = { excludeMethods: ['then'] };
function object(nameOrType, config) {
return lodash_1.default.tap(fakeObject(nameOrType, config, arguments.length), function (obj) {
return lodash_1.default.tap(fakeObject(nameOrType, config, arguments.length), (obj) => {
addToStringToDouble(obj, nameOrType);

@@ -32,24 +32,21 @@ });

};
var createTestDoublesForFunctionNames = function (names) {
return lodash_1.default.transform(names, function (acc, funcName) {
acc[funcName] = function_1.default("." + String(funcName));
}, {});
var createTestDoublesForFunctionNames = (names) => lodash_1.default.transform(names, (acc, funcName) => {
acc[funcName] = function_1.default(`.${String(funcName)}`);
}, {});
var ensureFunctionIsNotPassed = () => log_1.default.error('td.object', 'Functions are not valid arguments to `td.object` (as of testdouble@2.0.0). Please use `td.function()` or `td.constructor()` instead for creating fake functions.');
var ensureOtherGarbageIsNotPassed = () => log_1.default.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) => lodash_1.default.extend({}, DEFAULT_OPTIONS, config);
var addToStringToDouble = (fakeObject, nameOrType) => {
const name = nameOf(nameOrType);
fakeObject.toString = () => `[test double object${name ? ` for "${name}"` : ''}]`;
};
var ensureFunctionIsNotPassed = function () {
return log_1.default.error('td.object', 'Functions are not valid arguments to `td.object` (as of testdouble@2.0.0). Please use `td.function()` or `td.constructor()` instead for creating fake functions.');
};
var ensureOtherGarbageIsNotPassed = function () {
return log_1.default.error('td.object', "To create a fake object with td.object(), pass it a plain object that contains\nfunctions, an array of function names, or (if your runtime supports ES Proxy\nobjects) a string name.\n\nIf you passed td.object an instance of a custom type, consider passing the\ntype's constructor to `td.constructor()` instead.\n");
};
var withDefaults = function (config) {
return lodash_1.default.extend({}, DEFAULT_OPTIONS, config);
};
var addToStringToDouble = function (fakeObject, nameOrType) {
var name = nameOf(nameOrType);
fakeObject.toString = function () { return "[test double object" + (name ? " for \"" + name + "\"" : '') + "]"; };
};
var nameOf = function (nameOrType) {
return lodash_1.default.isString(nameOrType)
? nameOrType
: '';
};
var nameOf = (nameOrType) => lodash_1.default.isString(nameOrType)
? nameOrType
: '';
"use strict";
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
Object.defineProperty(exports, "__esModule", { value: true });
var theredoc = require("theredoc");
var lodash_1 = require("../wrap/lodash");
var log_1 = require("../log");
var function_1 = require("../function");
var store_1 = require("../store");
function proxy(name, _a) {
var excludeMethods = (_a === void 0 ? {} : _a).excludeMethods;
const theredoc = require("theredoc");
const lodash_1 = require("../wrap/lodash");
const log_1 = require("../log");
const function_1 = require("../function");
const store_1 = require("../store");
function proxy(name, { excludeMethods } = {}) {
ensureProxySupport(name);

@@ -18,13 +13,21 @@ return new Proxy({}, generateHandler(name, excludeMethods));

exports.default = proxy;
var ensureProxySupport = function (name) {
const ensureProxySupport = (name) => {
if (typeof Proxy === 'undefined') {
log_1.default.error('td.object', theredoc(templateObject_1 || (templateObject_1 = __makeTemplateObject([" The current runtime does not have Proxy support, which is what\n testdouble.js depends on when a string name is passed to `td.object()`.\n\n More details here:\n https://github.com/testdouble/testdouble.js/blob/master/docs/4-creating-test-doubles.md#objectobjectname\n\n Did you mean `td.object(['", "'])`?\n "], ["\\\n The current runtime does not have Proxy support, which is what\n testdouble.js depends on when a string name is passed to \\`td.object()\\`.\n\n More details here:\n https://github.com/testdouble/testdouble.js/blob/master/docs/4-creating-test-doubles.md#objectobjectname\n\n Did you mean \\`td.object(['", "'])\\`?\n "])), name));
log_1.default.error('td.object', theredoc `\
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 generateHandler = function (internalName, excludeMethods) { return ({
get: function (target, propKey) {
const generateHandler = (internalName, excludeMethods) => ({
get(target, propKey) {
return generateGet(target, propKey, internalName, excludeMethods);
}
}); };
var generateGet = function (target, propKey, internalName, excludeMethods) {
});
const generateGet = (target, propKey, internalName, excludeMethods) => {
if (propKey === Symbol('__is_proxy')) {

@@ -35,5 +38,5 @@ return true;

!lodash_1.default.includes(excludeMethods, propKey)) {
var nameWithProp = (internalName || '') + "." + String(propKey);
var tdFunc = function_1.default(nameWithProp);
var tdFuncProxy = new Proxy(tdFunc, generateHandler(nameWithProp, excludeMethods));
const nameWithProp = `${internalName || ''}.${String(propKey)}`;
const tdFunc = function_1.default(nameWithProp);
const tdFuncProxy = new Proxy(tdFunc, generateHandler(nameWithProp, excludeMethods));
store_1.default.registerAlias(tdFunc, tdFuncProxy);

@@ -44,2 +47,1 @@ target[propKey] = tdFuncProxy;

};
var templateObject_1;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var quibble = require("quibble");
var module_1 = require("./module");
var property_1 = require("./property");
const lodash_1 = require("../wrap/lodash");
const quibble = require("quibble");
const module_1 = require("./module");
const property_1 = require("./property");
quibble.ignoreCallsFromThisFile();
function default_1(target) {
if (lodash_1.default.isString(target)) {
return module_1.default.apply(void 0, arguments);
return module_1.default(...arguments);
}
else {
return property_1.default.apply(void 0, arguments);
return property_1.default(...arguments);
}
}
exports.default = default_1;
function replaceEsm(_modulePath, _namedExportReplacement, _defaultExportReplacement) {
if (!quibble.isLoaderLoaded()) {
throw new Error('testdouble ESM loader not loaded. You cannot replace ES modules without a loader. Run node with `--loader=testdouble`.');
}
// Sending arguments instead of the above arguments is crucial because `replaceEsModule`
// uses arguments.length to figure out what to do.
return module_1.replaceEsModule(...arguments);
}
exports.replaceEsm = replaceEsm;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
exports.default = (function (thing) {
return thing && thing.prototype && lodash_1.default.some(Object.getOwnPropertyNames(thing.prototype), function (property) {
return property !== 'constructor' && lodash_1.default.isFunction(thing.prototype[property]);
});
});
const lodash_1 = require("../wrap/lodash");
exports.default = (thing) => thing && thing.prototype && lodash_1.default.some(Object.getOwnPropertyNames(thing.prototype), property => property !== 'constructor' && lodash_1.default.isFunction(thing.prototype[property]));
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../../wrap/lodash");
const lodash_1 = require("../../wrap/lodash");
function fakeName(path, realThing) {
return path + ": " + nameFor(realThing);
return `${path}: ${nameFor(realThing)}`;
}
exports.default = fakeName;
var nameFor = function (realThing) {
const nameFor = (realThing) => {
if (!lodash_1.default.isFunction(realThing))

@@ -10,0 +10,0 @@ return '';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (function () {
exports.default = () => {
throw Error('Sorry, but CommonJS module replacement with td.replace() is only supported under Node.js runtimes.');
});
};
"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var quibble = require("quibble");
var imitate_1 = require("../../imitate");
var jest_module_1 = require("./jest-module");
var require_actual_1 = require("./require-actual");
var fake_name_1 = require("./fake-name");
const quibble = require("quibble");
const imitate_1 = require("../../imitate");
const jest_module_1 = require("./jest-module");
const require_actual_1 = require("./require-actual");
const fake_name_1 = require("./fake-name");
quibble.ignoreCallsFromThisFile();
function replaceModule(path, stub) {
function replaceCjsModule(path, stub) {
if (typeof jest === 'object')
return jest_module_1.default.apply(void 0, arguments);
return jest_module_1.default(...arguments);
if (arguments.length > 1) {
return quibble(path, stub);
}
var realThing = require_actual_1.default(path);
var fakeThing = imitate_1.default(realThing, fake_name_1.default(path, realThing));
const realThing = require_actual_1.default(path);
const fakeThing = imitate_1.default(realThing, fake_name_1.default(path, realThing));
quibble(path, fakeThing);
return fakeThing;
}
exports.default = replaceModule;
exports.default = replaceCjsModule;
async function replaceEsModule(path, namedExportsStub, defaultExportStub) {
if (typeof jest === 'object') {
throw new Error(`stubbing ES modules (${path}) under Jest is not yet supported`);
}
if (arguments.length > 1) {
return quibble.esm(path, namedExportsStub, defaultExportStub);
}
const { modulePath, module } = await quibble.esmImportWithPath(path);
const _a = imitate_1.default(module, fake_name_1.default(path, module)), { default: fakeDefaultExport = undefined } = _a, fakeNamedExports = __rest(_a, ["default"]);
await quibble.esm(modulePath, fakeNamedExports, fakeDefaultExport);
return Object.assign({ default: fakeDefaultExport }, fakeNamedExports);
}
exports.replaceEsModule = replaceEsModule;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var quibble = require("quibble");
var log_1 = require("../../log");
const quibble = require("quibble");
const log_1 = require("../../log");
quibble.ignoreCallsFromThisFile();
function jestModule(path, stub) {
var tdMock = require('../../index').mock;
const tdMock = require('../../index').mock;
if (!tdMock) {

@@ -12,3 +12,3 @@ log_1.default.error('td.replace', 'It appears the test is being run by Jest, but the testdouble-jest module has not been initialized, so testdouble.js cannot replace modules. For setup instructions, visit: https://github.com/testdouble/testdouble-jest');

else if (arguments.length > 1) {
tdMock(path, function () { return stub; }, { virtual: !moduleExists(tdMock, path) });
tdMock(path, () => stub, { virtual: !moduleExists(tdMock, path) });
return tdMock.requireMock(path);

@@ -22,3 +22,3 @@ }

exports.default = jestModule;
var moduleExists = function (tdMock, path) {
const moduleExists = function (tdMock, path) {
try {

@@ -25,0 +25,0 @@ // TODO: figure out how to invoke jest-resolve directly, because

"use strict";
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
Object.defineProperty(exports, "__esModule", { value: true });
var path_1 = require("path");
var quibble = require("quibble");
var theredoc = require("theredoc");
var log_1 = require("../../log");
const path_1 = require("path");
const quibble = require("quibble");
const theredoc = require("theredoc");
const log_1 = require("../../log");
quibble.ignoreCallsFromThisFile();
function requireActual(modulePath) {
var absolutePath = quibble.absolutify(modulePath);
var absolutePathLoadError, moduleNameLoadError;
const absolutePath = quibble.absolutify(modulePath);
let absolutePathLoadError, moduleNameLoadError;
// 1. Try just following quibble's inferred absolute path

@@ -34,3 +30,36 @@ try {

// 3. Give up, print a fancy error
log_1.default.error('td.replace', theredoc(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n failed to load the module being replaced.\n\n Why am I seeing this?\n ------------------------\n You called `td.replace('", "')`, but we failed to locate that\n module. How td.replace() works is that it first loads the actual module\n being faked in order to properly imitate it (i.e. to see whether it exports\n a default function, or an object of other named functions, and so on).\n\n How do I fix it?\n ----------------\n You probably specified a path that could not be resolved relative\n to your test file (or whatever listing from which you called `td.replace()`).\n Be sure you didn't specify the path relative to the subject under test!\n\n First, we tried to absolutify that path and require it, with:\n `require('", "')`\n\n But requiring that absolute path threw this error:\n \"", "\"\n\n Next, we tried to require it as you specified it (in case it's the name of\n a Node.js built-in or an npm package), with:\n `require('", "')`\n\n But that threw this error:\n \"", "\"\n\n Make sure the path specified exists (either relative to the call-site or\n as an installed module). If any of the paths above seem to be internal to\n testdouble.js or a dependency, that's probably a bug and you should open an\n issue.\n "], ["\n failed to load the module being replaced.\n\n Why am I seeing this?\n ------------------------\n You called \\`td.replace('", "')\\`, but we failed to locate that\n module. How td.replace() works is that it first loads the actual module\n being faked in order to properly imitate it (i.e. to see whether it exports\n a default function, or an object of other named functions, and so on).\n\n How do I fix it?\n ----------------\n You probably specified a path that could not be resolved relative\n to your test file (or whatever listing from which you called \\`td.replace()\\`).\n Be sure you didn't specify the path relative to the subject under test!\n\n First, we tried to absolutify that path and require it, with:\n \\`require('", "')\\`\n\n But requiring that absolute path threw this error:\n \"", "\"\n\n Next, we tried to require it as you specified it (in case it's the name of\n a Node.js built-in or an npm package), with:\n \\`require('", "')\\`\n\n But that threw this error:\n \"", "\"\n\n Make sure the path specified exists (either relative to the call-site or\n as an installed module). If any of the paths above seem to be internal to\n testdouble.js or a dependency, that's probably a bug and you should open an\n issue.\n "])), modulePath, absolutePath, firstLineOf(absolutePathLoadError.message), modulePath, firstLineOf(moduleNameLoadError.message)), 'https://github.com/testdouble/testdouble.js#module-replacement-with-nodejs');
log_1.default.error('td.replace', theredoc `
failed to load the module being replaced.
Why am I seeing this?
------------------------
You called \`td.replace('${modulePath}')\`, but we failed to locate that
module. How td.replace() works is that it first loads the actual module
being faked in order to properly imitate it (i.e. to see whether it exports
a default function, or an object of other named functions, and so on).
How do I fix it?
----------------
You probably specified a path that could not be resolved relative
to your test file (or whatever listing from which you called \`td.replace()\`).
Be sure you didn't specify the path relative to the subject under test!
First, we tried to absolutify that path and require it, with:
\`require('${absolutePath}')\`
But requiring that absolute path threw this error:
"${firstLineOf(absolutePathLoadError.message)}"
Next, we tried to require it as you specified it (in case it's the name of
a Node.js built-in or an npm package), with:
\`require('${modulePath}')\`
But that threw this error:
"${firstLineOf(moduleNameLoadError.message)}"
Make sure the path specified exists (either relative to the call-site or
as an installed module). If any of the paths above seem to be internal to
testdouble.js or a dependency, that's probably a bug and you should open an
issue.
`, 'https://github.com/testdouble/testdouble.js#module-replacement-with-nodejs');
}

@@ -41,2 +70,1 @@ exports.default = requireActual;

}
var templateObject_1;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var imitate_1 = require("../imitate");
var log_1 = require("../log");
var reset_1 = require("../reset");
var anything_1 = require("../stringify/anything");
const lodash_1 = require("../wrap/lodash");
const imitate_1 = require("../imitate");
const log_1 = require("../log");
const reset_1 = require("../reset");
const anything_1 = require("../stringify/anything");
function default_1(object, property, manualReplacement) {
var isManual = arguments.length > 2;
var realThingExists = object[property] ||
const isManual = arguments.length > 2;
const realThingExists = object[property] ||
Object.prototype.hasOwnProperty.call(object, property);
if (isManual || realThingExists) {
var realThing_1 = object[property];
return lodash_1.default.tap(getFake(isManual, property, manualReplacement, realThing_1), function (fakeThing) {
const realThing = object[property];
return lodash_1.default.tap(getFake(isManual, property, manualReplacement, realThing), (fakeThing) => {
object[property] = fakeThing;
reset_1.default.onNextReset(function () {
reset_1.default.onNextReset(() => {
if (realThingExists) {
object[property] = realThing_1;
object[property] = realThing;
}

@@ -27,7 +27,7 @@ else {

else {
log_1.default.error('td.replace', "No \"" + property + "\" property was found.");
log_1.default.error('td.replace', `No "${property}" property was found.`);
}
}
exports.default = default_1;
var getFake = function (isManual, property, manualReplacement, realThing) {
var getFake = (isManual, property, manualReplacement, realThing) => {
if (isManual) {

@@ -41,8 +41,8 @@ warnIfTypeMismatch(property, manualReplacement, realThing);

};
var warnIfTypeMismatch = function (property, fakeThing, realThing) {
var fakeType = typeof fakeThing;
var realType = typeof realThing;
var warnIfTypeMismatch = (property, fakeThing, realThing) => {
const fakeType = typeof fakeThing;
const realType = typeof realThing;
if (realThing !== undefined && fakeType !== realType) {
log_1.default.warn('td.replace', "property \"" + property + "\" " + anything_1.default(realThing) + " (" + lodash_1.default.capitalize(realType) + ") was replaced with " + anything_1.default(fakeThing) + ", which has a different type (" + lodash_1.default.capitalize(fakeType) + ").");
log_1.default.warn('td.replace', `property "${property}" ${anything_1.default(realThing)} (${lodash_1.default.capitalize(realType)}) was replaced with ${anything_1.default(fakeThing)}, which has a different type (${lodash_1.default.capitalize(fakeType)}).`);
}
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var quibble = require("quibble");
var store_1 = require("./store");
var onResetHandlers = [];
var onNextResetHandlers = [];
exports.default = lodash_1.default.tap(function () {
const lodash_1 = require("./wrap/lodash");
const quibble = require("quibble");
const store_1 = require("./store");
const onResetHandlers = [];
let onNextResetHandlers = [];
exports.default = lodash_1.default.tap(() => {
store_1.default.reset();
quibble.reset();
lodash_1.default.each(onResetHandlers, function (resetHandler) {
return resetHandler();
});
lodash_1.default.each(onNextResetHandlers, function (resetHandler) {
return resetHandler();
});
lodash_1.default.each(onResetHandlers, (resetHandler) => resetHandler());
lodash_1.default.each(onNextResetHandlers, (resetHandler) => resetHandler());
onNextResetHandlers = [];
}, function (reset) {
reset.onReset = function (func) {
return onResetHandlers.push(func);
};
reset.onNextReset = function (func) {
return onNextResetHandlers.push(func);
};
}, (reset) => {
reset.onReset = (func) => onResetHandlers.push(func);
reset.onNextReset = (func) => onNextResetHandlers.push(func);
});
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var create_promise_1 = require("../share/create-promise");
const create_promise_1 = require("../share/create-promise");
function deliverOutcome(stubbing, call) {

@@ -5,0 +5,0 @@ switch (stubbing.type) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var stubbing_register_1 = require("../value/stubbing-register");
var args_match_1 = require("../args-match");
const lodash_1 = require("../wrap/lodash");
const stubbing_register_1 = require("../value/stubbing-register");
const args_match_1 = require("../args-match");
function findLastStubbingMatch(double, call) {
return lodash_1.default.findLast(stubbing_register_1.default.instance.get(double), function (stubbing) {
return args_match_1.default(stubbing.args, call.args, stubbing.config) && stubbing.hasTimesRemaining;
});
return lodash_1.default.findLast(stubbing_register_1.default.instance.get(double), (stubbing) => args_match_1.default(stubbing.args, call.args, stubbing.config) && stubbing.hasTimesRemaining);
}
exports.default = findLastStubbingMatch;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var find_last_stubbing_match_1 = require("./find-last-stubbing-match");
var invoke_callbacks_1 = require("./invoke-callbacks");
var notify_after_satisfaction_1 = require("../matchers/notify-after-satisfaction");
var deliver_outcome_1 = require("./deliver-outcome");
const find_last_stubbing_match_1 = require("./find-last-stubbing-match");
const invoke_callbacks_1 = require("./invoke-callbacks");
const notify_after_satisfaction_1 = require("../matchers/notify-after-satisfaction");
const deliver_outcome_1 = require("./deliver-outcome");
function satisfy(double, call) {
var stubbing = find_last_stubbing_match_1.default(double, call);
const stubbing = find_last_stubbing_match_1.default(double, call);
if (stubbing) {

@@ -10,0 +10,0 @@ stubbing.addSatisfyingCall(call);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var is_callback_1 = require("../matchers/is-callback");
var call_later_1 = require("../share/call-later");
const lodash_1 = require("../wrap/lodash");
const is_callback_1 = require("../matchers/is-callback");
const call_later_1 = require("../share/call-later");
function invokeCallbacks(stubbing, call) {
lodash_1.default.each(stubbing.args, function (stubbingArg, i) {
lodash_1.default.each(stubbing.args, (stubbingArg, i) => {
if (is_callback_1.default(stubbingArg)) {
var actualCallback = call.args[i];
const actualCallback = call.args[i];
call_later_1.default(actualCallback, callbackArgs(stubbing, stubbingArg), stubbing.options.defer, stubbing.options.delay);

@@ -11,0 +11,0 @@ }

"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
const lodash_1 = require("../wrap/lodash");
function callLater(func, args, defer, delay) {
if (delay) {
lodash_1.default.delay.apply(lodash_1.default, __spreadArrays([func, delay], args));
lodash_1.default.delay(func, delay, ...args);
}
else if (defer) {
lodash_1.default.defer.apply(lodash_1.default, __spreadArrays([func], args));
lodash_1.default.defer(func, ...args);
}
else {
func.apply(void 0, args);
func(...args);
}
}
exports.default = callLater;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var config_1 = require("../config");
var ensure_promise_1 = require("../log/ensure-promise");
var call_later_1 = require("../share/call-later");
const config_1 = require("../config");
const ensure_promise_1 = require("../log/ensure-promise");
const call_later_1 = require("../share/call-later");
function createPromise(stubbing, willResolve) {
var Promise = config_1.default().promiseConstructor;
const Promise = config_1.default().promiseConstructor;
ensure_promise_1.default('error');
var value = stubbing.currentOutcome;
return new Promise(function (resolve, reject) {
call_later_1.default(function () {
return willResolve ? resolve(value) : reject(value);
}, [value], stubbing.options.defer, stubbing.options.delay);
const value = stubbing.currentOutcome;
return new Promise((resolve, reject) => {
call_later_1.default(() => willResolve ? resolve(value) : reject(value), [value], stubbing.options.defer, stubbing.options.delay);
});
}
exports.default = createPromise;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var args_match_1 = require("../args-match");
var index_1 = require("./index");
var callHistory = []; // <-- remember this to pop our DSL of when(<call>)/verify(<call>)
index_1.default.onReset(function () { callHistory = []; });
const lodash_1 = require("../wrap/lodash");
const args_match_1 = require("../args-match");
const index_1 = require("./index");
let callHistory = []; // <-- remember this to pop our DSL of when(<call>)/verify(<call>)
index_1.default.onReset(() => { callHistory = []; });
exports.default = {
log: function (testDouble, args, context) {
index_1.default.for(testDouble).calls.push({ args: args, context: context, cloneArgs: lodash_1.default.cloneDeep(args) });
return callHistory.push({ testDouble: testDouble, args: args, context: context });
log(testDouble, args, context) {
index_1.default.for(testDouble).calls.push({ args, context, cloneArgs: lodash_1.default.cloneDeep(args) });
return callHistory.push({ testDouble, args, context });
},
pop: function () {
pop() {
return lodash_1.default.tap(callHistory.pop(), function (call) {

@@ -20,4 +20,4 @@ if (call != null) {

},
wasInvoked: function (testDouble, args, config) {
var matchingInvocationCount = this.where(testDouble, args, config).length;
wasInvoked(testDouble, args, config) {
const matchingInvocationCount = this.where(testDouble, args, config).length;
if (config.times != null) {

@@ -30,11 +30,11 @@ return matchingInvocationCount === config.times;

},
where: function (testDouble, args, config) {
where(testDouble, args, config) {
return lodash_1.default.filter(index_1.default.for(testDouble).calls, function (call) {
var pastArgs = config.cloneArgs ? call.cloneArgs : call.args;
const pastArgs = config.cloneArgs ? call.cloneArgs : call.args;
return args_match_1.default(args, pastArgs, config);
});
},
for: function (testDouble) {
for(testDouble) {
return index_1.default.for(testDouble).calls;
}
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var events_1 = require("events");
var storeEmitter = new events_1.EventEmitter();
var globalStore = [];
var store = {
onReset: function (func) {
const lodash_1 = require("../wrap/lodash");
const events_1 = require("events");
const storeEmitter = new events_1.EventEmitter();
let globalStore = [];
const store = {
onReset(func) {
storeEmitter.on('reset', func);
},
reset: function () {
reset() {
globalStore = [];
storeEmitter.emit('reset');
},
for: function (testDouble, createIfNew) {
if (createIfNew === void 0) { createIfNew = true; }
var entry = lodash_1.default.find(globalStore, function (e) { return testDouble === e.testDouble || testDouble === e.alias; });
for(testDouble, createIfNew = true) {
const entry = lodash_1.default.find(globalStore, e => testDouble === e.testDouble || testDouble === e.alias);
if (entry) {

@@ -23,3 +22,3 @@ return entry;

return lodash_1.default.tap({
testDouble: testDouble,
testDouble,
stubbings: [],

@@ -33,3 +32,3 @@ calls: [],

},
registerAlias: function (testDouble, alias) {
registerAlias(testDouble, alias) {
store.for(testDouble).alias = alias;

@@ -36,0 +35,0 @@ }

"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var args_match_1 = require("../args-match");
var is_callback_1 = require("../matchers/is-callback");
var notify_after_satisfaction_1 = require("../matchers/notify-after-satisfaction");
var config_1 = require("../config");
var log_1 = require("../log");
var index_1 = require("./index");
const lodash_1 = require("../wrap/lodash");
const args_match_1 = require("../args-match");
const is_callback_1 = require("../matchers/is-callback");
const notify_after_satisfaction_1 = require("../matchers/notify-after-satisfaction");
const config_1 = require("../config");
const log_1 = require("../log");
const index_1 = require("./index");
exports.default = {
add: function (testDouble, args, stubbedValues, config) {
add(testDouble, args, stubbedValues, config) {
return index_1.default.for(testDouble).stubbings.push({
callCount: 0,
stubbedValues: stubbedValues,
stubbedValues,
args: config.cloneArgs ? lodash_1.default.cloneDeep(args) : args,
config: config
config
});
},
invoke: function (testDouble, actualArgs, actualContext) {
var stubbing = stubbingFor(testDouble, actualArgs);
invoke(testDouble, actualArgs, actualContext) {
const stubbing = stubbingFor(testDouble, actualArgs);
if (stubbing) {

@@ -33,13 +26,9 @@ notify_after_satisfaction_1.default(stubbing.args, actualArgs);

},
for: function (testDouble) {
for(testDouble) {
return index_1.default.for(testDouble).stubbings;
}
};
var stubbingFor = function (testDouble, actualArgs) {
return lodash_1.default.findLast(index_1.default.for(testDouble).stubbings, function (stubbing) {
return isSatisfied(stubbing, actualArgs);
});
};
var executePlan = function (stubbing, actualArgs, actualContext) {
var value = stubbedValueFor(stubbing);
var stubbingFor = (testDouble, actualArgs) => lodash_1.default.findLast(index_1.default.for(testDouble).stubbings, stubbing => isSatisfied(stubbing, actualArgs));
var executePlan = (stubbing, actualArgs, actualContext) => {
const value = stubbedValueFor(stubbing);
stubbing.callCount += 1;

@@ -55,5 +44,5 @@ invokeCallbackFor(stubbing, actualArgs);

};
var invokeCallbackFor = function (stubbing, actualArgs) {
var invokeCallbackFor = (stubbing, actualArgs) => {
if (lodash_1.default.some(stubbing.args, is_callback_1.default)) {
lodash_1.default.each(stubbing.args, function (expectedArg, i) {
lodash_1.default.each(stubbing.args, (expectedArg, i) => {
if (is_callback_1.default(expectedArg)) {

@@ -65,3 +54,3 @@ callCallback(stubbing, actualArgs[i], callbackArgs(stubbing, expectedArg));

};
var callbackArgs = function (stubbing, expectedArg) {
var callbackArgs = (stubbing, expectedArg) => {
if (expectedArg.args != null) {

@@ -77,40 +66,41 @@ return expectedArg.args;

};
var callCallback = function (stubbing, callback, args) {
var callCallback = (stubbing, callback, args) => {
if (stubbing.config.delay) {
lodash_1.default.delay.apply(lodash_1.default, __spreadArrays([callback, stubbing.config.delay], args));
lodash_1.default.delay(callback, stubbing.config.delay, ...args);
}
else if (stubbing.config.defer) {
lodash_1.default.defer.apply(lodash_1.default, __spreadArrays([callback], args));
lodash_1.default.defer(callback, ...args);
}
else {
callback.apply(void 0, args); // eslint-disable-line
callback(...args); // eslint-disable-line
}
};
var createPromise = function (stubbing, value, willResolve) {
var Promise = config_1.default().promiseConstructor;
var createPromise = (stubbing, value, willResolve) => {
const Promise = config_1.default().promiseConstructor;
ensurePromise(Promise);
return new Promise(function (resolve, reject) {
callCallback(stubbing, function () {
return willResolve ? resolve(value) : reject(value);
}, [value]);
return new Promise((resolve, reject) => {
callCallback(stubbing, () => willResolve ? resolve(value) : reject(value), [value]);
});
};
var stubbedValueFor = function (stubbing) {
return stubbing.callCount < stubbing.stubbedValues.length
? stubbing.stubbedValues[stubbing.callCount]
: lodash_1.default.last(stubbing.stubbedValues);
};
var isSatisfied = function (stubbing, actualArgs) {
return args_match_1.default(stubbing.args, actualArgs, stubbing.config) &&
hasTimesRemaining(stubbing);
};
var hasTimesRemaining = function (stubbing) {
return stubbing.config.times == null
? true
: stubbing.callCount < stubbing.config.times;
};
var ensurePromise = function (Promise) {
var stubbedValueFor = (stubbing) => stubbing.callCount < stubbing.stubbedValues.length
? stubbing.stubbedValues[stubbing.callCount]
: lodash_1.default.last(stubbing.stubbedValues);
var isSatisfied = (stubbing, actualArgs) => args_match_1.default(stubbing.args, actualArgs, stubbing.config) &&
hasTimesRemaining(stubbing);
var hasTimesRemaining = (stubbing) => stubbing.config.times == null
? true
: stubbing.callCount < stubbing.config.times;
var ensurePromise = (Promise) => {
if (Promise == null) {
return log_1.default.error('td.when', "no promise constructor is set (perhaps this runtime lacks a native Promise\nfunction?), which means this stubbing can't return a promise to your\nsubject under test, resulting in this error. To resolve the issue, set\na promise constructor with `td.config`, like this:\n\n td.config({\n promiseConstructor: require('bluebird')\n })");
return log_1.default.error('td.when', `\
no promise constructor is set (perhaps this runtime lacks a native Promise
function?), which means this stubbing can't return a promise to your
subject under test, resulting in this error. To resolve the issue, set
a promise constructor with \`td.config\`, like this:
td.config({
promiseConstructor: require('bluebird')
})\
`);
}
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var is_matcher_1 = require("../matchers/is-matcher");
var stringifyObject = require("stringify-object-es5");
exports.default = (function (anything) {
const lodash_1 = require("../wrap/lodash");
const is_matcher_1 = require("../matchers/is-matcher");
const stringifyObject = require("stringify-object-es5");
exports.default = (anything) => {
if (lodash_1.default.isString(anything)) {

@@ -21,3 +21,3 @@ return stringifyString(anything);

inlineCharacterLimit: 65,
transform: function (obj, prop, originalResult) {
transform(obj, prop, originalResult) {
if (is_matcher_1.default(obj[prop])) {

@@ -32,7 +32,5 @@ return obj[prop].__name;

}
});
var stringifyString = function (string) {
return lodash_1.default.includes(string, '\n')
? "\"\"\"\n" + string + "\n\"\"\""
: "\"" + string.replace(new RegExp('"', 'g'), '\\"') + "\"";
};
var stringifyString = (string) => lodash_1.default.includes(string, '\n')
? `"""\n${string}\n"""`
: `"${string.replace(new RegExp('"', 'g'), '\\"')}"`;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var anything_1 = require("./anything");
exports.default = (function (args, joiner, wrapper) {
if (joiner === void 0) { joiner = ', '; }
if (wrapper === void 0) { wrapper = ''; }
return lodash_1.default.map(args, function (arg) {
return "" + wrapper + anything_1.default(arg) + wrapper;
}).join(joiner);
});
const lodash_1 = require("../wrap/lodash");
const anything_1 = require("./anything");
exports.default = (args, joiner = ', ', wrapper = '') => lodash_1.default.map(args, arg => `${wrapper}${anything_1.default(arg)}${wrapper}`).join(joiner);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var instance = null;
var CallLog = /** @class */ (function () {
function CallLog() {
let instance = null;
class CallLog {
static get instance() {
if (instance)
return instance;
instance = new CallLog();
return instance;
}
static reset() {
instance = null;
}
constructor() {
this.calls = new Map();
this.callHistory = [];
}
Object.defineProperty(CallLog, "instance", {
get: function () {
if (instance)
return instance;
instance = new CallLog();
return instance;
},
enumerable: true,
configurable: true
});
CallLog.reset = function () {
instance = null;
};
CallLog.prototype.log = function (double, call) {
this.callHistory.push({ double: double, call: call });
log(double, call) {
this.callHistory.push({ double, call });
if (this.calls.has(double)) {

@@ -30,8 +26,8 @@ this.calls.get(double).push(call);

}
};
CallLog.prototype.for = function (double) {
}
for(double) {
return this.calls.get(double);
};
CallLog.prototype.pop = function () {
var lastCall = this.callHistory.pop();
}
pop() {
const lastCall = this.callHistory.pop();
if (lastCall && this.calls.has(lastCall.double)) {

@@ -41,5 +37,4 @@ this.calls.get(lastCall.double).pop();

return lastCall;
};
return CallLog;
}());
}
}
exports.default = CallLog;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Call = /** @class */ (function () {
function Call(context, args) {
class Call {
constructor(context, args) {
this.context = context;
this.args = args;
}
return Call;
}());
}
exports.default = Call;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var Double = /** @class */ (function () {
function Double(name, real, parent) {
const lodash_1 = require("../wrap/lodash");
class Double {
static create(name, real, parent, fakeCreator) {
const double = new Double(name, real, parent);
if (fakeCreator)
double.fake = fakeCreator(double);
return double;
}
constructor(name, real, parent) {
this.name = name;

@@ -14,37 +20,20 @@ this.real = real;

}
Double.create = function (name, real, parent, fakeCreator) {
var double = new Double(name, real, parent);
if (fakeCreator)
double.fake = fakeCreator(double);
return double;
};
Double.prototype.addChild = function (child) {
addChild(child) {
this.children.add(child);
child.parent = this;
};
Object.defineProperty(Double.prototype, "fullName", {
get: function () {
if (!lodash_1.default.some(lodash_1.default.map(this.ancestors, 'name')))
return this.name;
return lodash_1.default.map(this.ancestors.concat(this), function (ancestor) {
return ancestor.name == null ? '(unnamed)' : ancestor.name;
}).join('.');
},
enumerable: true,
configurable: true
});
Object.defineProperty(Double.prototype, "ancestors", {
get: function () {
if (!this.parent)
return [];
return this.parent.ancestors.concat(this.parent);
},
enumerable: true,
configurable: true
});
Double.prototype.toString = function () {
return this.fullName == null ? '[test double (unnamed)]' : "[test double for \"" + this.fullName + "\"]";
};
return Double;
}());
}
get fullName() {
if (!lodash_1.default.some(lodash_1.default.map(this.ancestors, 'name')))
return this.name;
return lodash_1.default.map(this.ancestors.concat(this), (ancestor) => ancestor.name == null ? '(unnamed)' : ancestor.name).join('.');
}
get ancestors() {
if (!this.parent)
return [];
return this.parent.ancestors.concat(this.parent);
}
toString() {
return this.fullName == null ? '[test double (unnamed)]' : `[test double for "${this.fullName}"]`;
}
}
exports.default = Double;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var instance = null;
var StubbingRegister = /** @class */ (function () {
function StubbingRegister() {
let instance = null;
class StubbingRegister {
static get instance() {
if (instance)
return instance;
instance = new StubbingRegister();
return instance;
}
static reset() {
instance = null;
}
constructor() {
this.stubbings = new Map();
}
Object.defineProperty(StubbingRegister, "instance", {
get: function () {
if (instance)
return instance;
instance = new StubbingRegister();
return instance;
},
enumerable: true,
configurable: true
});
StubbingRegister.reset = function () {
instance = null;
};
StubbingRegister.prototype.add = function (double, stubbing) {
add(double, stubbing) {
if (this.stubbings.has(double)) {

@@ -28,8 +24,7 @@ this.stubbings.get(double).push(stubbing);

}
};
StubbingRegister.prototype.get = function (double) {
}
get(double) {
return this.stubbings.get(double);
};
return StubbingRegister;
}());
}
}
exports.default = StubbingRegister;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var Stubbing = /** @class */ (function () {
function Stubbing(type, args, outcomes, options) {
if (options === void 0) { options = {}; }
const lodash_1 = require("../wrap/lodash");
class Stubbing {
constructor(type, args, outcomes, options = {}) {
this.type = type;

@@ -13,29 +12,20 @@ this.args = args;

}
Object.defineProperty(Stubbing.prototype, "hasTimesRemaining", {
get: function () {
if (this.options.times == null)
return true;
return this.satisfyingCalls.size < this.options.times;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Stubbing.prototype, "currentOutcome", {
get: function () {
var outcomeIndex = Math.max(0, this.satisfyingCalls.size - 1);
if (outcomeIndex < this.outcomes.length) {
return this.outcomes[outcomeIndex];
}
else {
return lodash_1.default.last(this.outcomes);
}
},
enumerable: true,
configurable: true
});
Stubbing.prototype.addSatisfyingCall = function (call) {
get hasTimesRemaining() {
if (this.options.times == null)
return true;
return this.satisfyingCalls.size < this.options.times;
}
get currentOutcome() {
const outcomeIndex = Math.max(0, this.satisfyingCalls.size - 1);
if (outcomeIndex < this.outcomes.length) {
return this.outcomes[outcomeIndex];
}
else {
return lodash_1.default.last(this.outcomes);
}
}
addSatisfyingCall(call) {
this.satisfyingCalls.add(call);
};
return Stubbing;
}());
}
}
exports.default = Stubbing;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var args_match_1 = require("./args-match");
var calls_1 = require("./store/calls");
var log_1 = require("./log");
var store_1 = require("./store");
var arguments_1 = require("./stringify/arguments");
var stubbings_1 = require("./store/stubbings");
var notify_after_satisfaction_1 = require("./matchers/notify-after-satisfaction");
exports.default = (function (__userDoesRehearsalInvocationHere__, config) {
if (config === void 0) { config = {}; }
var last = calls_1.default.pop();
const lodash_1 = require("./wrap/lodash");
const args_match_1 = require("./args-match");
const calls_1 = require("./store/calls");
const log_1 = require("./log");
const store_1 = require("./store");
const arguments_1 = require("./stringify/arguments");
const stubbings_1 = require("./store/stubbings");
const notify_after_satisfaction_1 = require("./matchers/notify-after-satisfaction");
exports.default = (__userDoesRehearsalInvocationHere__, config = {}) => {
const last = calls_1.default.pop();
ensureRehearsalOccurred(last);

@@ -22,34 +21,38 @@ if (calls_1.default.wasInvoked(last.testDouble, last.args, config)) {

}
});
var ensureRehearsalOccurred = function (last) {
};
var ensureRehearsalOccurred = (last) => {
if (!last) {
log_1.default.error('td.verify', "No test double invocation detected for `verify()`.\n\n Usage:\n verify(myTestDouble('foo'))");
log_1.default.error('td.verify', `\
No test double invocation detected for \`verify()\`.
Usage:
verify(myTestDouble('foo'))\
`);
}
};
var notifyMatchers = function (testDouble, expectedArgs, config) {
lodash_1.default.each(calls_1.default.where(testDouble, expectedArgs, config), function (invocation) {
const notifyMatchers = (testDouble, expectedArgs, config) => {
lodash_1.default.each(calls_1.default.where(testDouble, expectedArgs, config), (invocation) => {
notify_after_satisfaction_1.default(expectedArgs, invocation.args);
});
};
var warnIfStubbed = function (testDouble, actualArgs) {
if (lodash_1.default.some(stubbings_1.default.for(testDouble), function (stubbing) {
return args_match_1.default(stubbing.args, actualArgs, stubbing.config);
})) {
log_1.default.warn('td.verify', "test double" + stringifyName(testDouble) + " was both stubbed and verified with arguments (" + arguments_1.default(actualArgs) + "), which is redundant and probably unnecessary.", 'https://github.com/testdouble/testdouble.js/blob/master/docs/B-frequently-asked-questions.md#why-shouldnt-i-call-both-tdwhen-and-tdverify-for-a-single-interaction-with-a-test-double');
var warnIfStubbed = (testDouble, actualArgs) => {
if (lodash_1.default.some(stubbings_1.default.for(testDouble), (stubbing) => args_match_1.default(stubbing.args, actualArgs, stubbing.config))) {
log_1.default.warn('td.verify', `test double${stringifyName(testDouble)} was both stubbed and verified with arguments (${arguments_1.default(actualArgs)}), which is redundant and probably unnecessary.`, 'https://github.com/testdouble/testdouble.js/blob/master/docs/B-frequently-asked-questions.md#why-shouldnt-i-call-both-tdwhen-and-tdverify-for-a-single-interaction-with-a-test-double');
}
};
var unsatisfiedErrorMessage = function (testDouble, args, config) {
return baseSummary(testDouble, args, config) +
matchedInvocationSummary(testDouble, args, config) +
invocationSummary(testDouble, args, config);
var unsatisfiedErrorMessage = (testDouble, args, config) => baseSummary(testDouble, args, config) +
matchedInvocationSummary(testDouble, args, config) +
invocationSummary(testDouble, args, config);
var stringifyName = (testDouble) => {
const name = store_1.default.for(testDouble).name;
return name ? ` \`${name}\`` : '';
};
var stringifyName = function (testDouble) {
var name = store_1.default.for(testDouble).name;
return name ? " `" + name + "`" : '';
};
var baseSummary = function (testDouble, args, config) {
return "Unsatisfied verification on test double" + stringifyName(testDouble) + ".\n\n Wanted:\n - called with `(" + arguments_1.default(args) + ")`" + timesMessage(config) + ignoreMessage(config) + ".";
};
var invocationSummary = function (testDouble, args, config) {
var calls = calls_1.default.for(testDouble);
var baseSummary = (testDouble, args, config) => `\
Unsatisfied verification on test double${stringifyName(testDouble)}.
Wanted:
- called with \`(${arguments_1.default(args)})\`${timesMessage(config)}${ignoreMessage(config)}.\
`;
var invocationSummary = (testDouble, args, config) => {
const calls = calls_1.default.for(testDouble);
if (calls.length === 0) {

@@ -59,10 +62,8 @@ return '\n\n But there were no invocations of the test double.';

else {
return lodash_1.default.reduce(calls, function (desc, call) {
return desc + ("\n - called with `(" + arguments_1.default(call.args) + ")`.");
}, '\n\n All calls of the test double, in order were:');
return lodash_1.default.reduce(calls, (desc, call) => desc + `\n - called with \`(${arguments_1.default(call.args)})\`.`, '\n\n All calls of the test double, in order were:');
}
};
var matchedInvocationSummary = function (testDouble, args, config) {
var calls = calls_1.default.where(testDouble, args, config);
var expectedCalls = config.times || 0;
var matchedInvocationSummary = (testDouble, args, config) => {
const calls = calls_1.default.where(testDouble, args, config);
const expectedCalls = config.times || 0;
if (calls.length === 0 || calls.length > expectedCalls) {

@@ -72,19 +73,11 @@ return '';

else {
return lodash_1.default.reduce(lodash_1.default.groupBy(calls, 'args'), function (desc, callsMatchingArgs, args) {
return desc + ("\n - called " + pluralize(callsMatchingArgs.length, 'time') + " with `(" + arguments_1.default(callsMatchingArgs[0].args) + ")`.");
}, "\n\n " + pluralize(calls.length, 'call') + " that satisfied this verification:");
return lodash_1.default.reduce(lodash_1.default.groupBy(calls, 'args'), (desc, callsMatchingArgs, args) => desc + `\n - called ${pluralize(callsMatchingArgs.length, 'time')} with \`(${arguments_1.default(callsMatchingArgs[0].args)})\`.`, `\n\n ${pluralize(calls.length, 'call')} that satisfied this verification:`);
}
};
var pluralize = function (x, msg) {
return x + " " + msg + (x === 1 ? '' : 's');
};
var timesMessage = function (config) {
return config.times != null
? " " + pluralize(config.times, 'time')
: '';
};
var ignoreMessage = function (config) {
return config.ignoreExtraArgs != null
? ', ignoring any additional arguments'
: '';
};
var pluralize = (x, msg) => `${x} ${msg}${x === 1 ? '' : 's'}`;
var timesMessage = (config) => config.times != null
? ` ${pluralize(config.times, 'time')}`
: '';
var ignoreMessage = (config) => config.ignoreExtraArgs != null
? ', ignoring any additional arguments'
: '';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var pop_demonstration_1 = require("./pop-demonstration");
var did_call_occur_1 = require("./did-call-occur");
var notify_satisfied_matchers_1 = require("./notify-satisfied-matchers");
var warn_if_also_stubbed_1 = require("./warn-if-also-stubbed");
var fail_1 = require("./fail");
const pop_demonstration_1 = require("./pop-demonstration");
const did_call_occur_1 = require("./did-call-occur");
const notify_satisfied_matchers_1 = require("./notify-satisfied-matchers");
const warn_if_also_stubbed_1 = require("./warn-if-also-stubbed");
const fail_1 = require("./fail");
function verify(__userInvokesDemonstrationHere__, config) {
var _a = pop_demonstration_1.default(), double = _a.double, call = _a.call;
const { double, call } = pop_demonstration_1.default();
if (did_call_occur_1.default(double, call, config)) {

@@ -11,0 +11,0 @@ notify_satisfied_matchers_1.default(double, call, config);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = '3.14.0';
exports.default = '3.15.0';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./wrap/lodash");
var callback_1 = require("./callback");
var is_callback_1 = require("./matchers/is-callback");
var calls_1 = require("./store/calls");
var log_1 = require("./log");
var stubbings_1 = require("./store/stubbings");
var config_1 = require("./config");
function when(__userDoesRehearsalInvocationHere__, config) {
if (config === void 0) { config = {}; }
const lodash_1 = require("./wrap/lodash");
const callback_1 = require("./callback");
const is_callback_1 = require("./matchers/is-callback");
const calls_1 = require("./store/calls");
const log_1 = require("./log");
const stubbings_1 = require("./store/stubbings");
const config_1 = require("./config");
function when(__userDoesRehearsalInvocationHere__, config = {}) {
return ({
thenReturn: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenReturn(...stubbedValues) {
return addStubbing(stubbedValues, config, 'thenReturn');
},
thenCallback: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenCallback(...stubbedValues) {
return addStubbing(stubbedValues, config, 'thenCallback');
},
thenDo: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenDo(...stubbedValues) {
return addStubbing(stubbedValues, config, 'thenDo');
},
thenThrow: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenThrow(...stubbedValues) {
return addStubbing(stubbedValues, config, 'thenThrow');
},
thenResolve: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenResolve(...stubbedValues) {
warnIfPromiseless();
return addStubbing(stubbedValues, config, 'thenResolve');
},
thenReject: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenReject(...stubbedValues) {
warnIfPromiseless();

@@ -61,5 +36,5 @@ return addStubbing(stubbedValues, config, 'thenReject');

function addStubbing(stubbedValues, config, plan) {
var last = calls_1.default.pop();
const last = calls_1.default.pop();
ensureRehearsalOccurred(last);
lodash_1.default.assign(config, { plan: plan });
lodash_1.default.assign(config, { plan });
stubbings_1.default.add(last.testDouble, concatImpliedCallback(last.args, config), stubbedValues, config);

@@ -70,3 +45,8 @@ return last.testDouble;

if (!last) {
return log_1.default.error('td.when', "No test double invocation call detected for `when()`.\n\n Usage:\n when(myTestDouble('foo')).thenReturn('bar')");
return log_1.default.error('td.when', `\
No test double invocation call detected for \`when()\`.
Usage:
when(myTestDouble('foo')).thenReturn('bar')\
`);
}

@@ -87,4 +67,12 @@ }

if (config_1.default().promiseConstructor == null) {
log_1.default.warn('td.when', "no promise constructor is set, so this `thenResolve` or `thenReject` stubbing\nwill fail if it's satisfied by an invocation on the test double. You can tell\ntestdouble.js which promise constructor to use with `td.config`, like so:\n\n td.config({\n promiseConstructor: require('bluebird')\n })");
log_1.default.warn('td.when', `\
no promise constructor is set, so this \`thenResolve\` or \`thenReject\` stubbing
will fail if it's satisfied by an invocation on the test double. You can tell
testdouble.js which promise constructor to use with \`td.config\`, like so:
td.config({
promiseConstructor: require('bluebird')
})\
`);
}
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("../wrap/lodash");
var is_callback_1 = require("../matchers/is-callback");
var callback_1 = require("../callback");
const lodash_1 = require("../wrap/lodash");
const is_callback_1 = require("../matchers/is-callback");
const callback_1 = require("../callback");
function default_1(type, args) {

@@ -7,0 +7,0 @@ if (type === 'thenCallback' && !lodash_1.default.some(args, is_callback_1.default)) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ensure_promise_1 = require("../log/ensure-promise");
const ensure_promise_1 = require("../log/ensure-promise");
function chainStubbing(double, completeStubbing) {
return {
thenReturn: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenReturn(...stubbedValues) {
completeStubbing('thenReturn', stubbedValues);
return double.fake;
},
thenCallback: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenCallback(...stubbedValues) {
completeStubbing('thenCallback', stubbedValues);
return double.fake;
},
thenDo: function () {
var stubbedActions = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedActions[_i] = arguments[_i];
}
thenDo(...stubbedActions) {
completeStubbing('thenDo', stubbedActions);
return double.fake;
},
thenThrow: function () {
var stubbedErrors = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedErrors[_i] = arguments[_i];
}
thenThrow(...stubbedErrors) {
completeStubbing('thenThrow', stubbedErrors);
return double.fake;
},
thenResolve: function () {
var stubbedValues = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedValues[_i] = arguments[_i];
}
thenResolve(...stubbedValues) {
ensure_promise_1.default('warn');

@@ -47,7 +27,3 @@ completeStubbing('thenResolve', stubbedValues);

},
thenReject: function () {
var stubbedErrors = [];
for (var _i = 0; _i < arguments.length; _i++) {
stubbedErrors[_i] = arguments[_i];
}
thenReject(...stubbedErrors) {
ensure_promise_1.default('warn');

@@ -54,0 +30,0 @@ completeStubbing('thenReject', stubbedErrors);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var log_1 = require("../log");
const log_1 = require("../log");
function ensureRehearsal(rehearsal) {
if (!rehearsal) {
log_1.default.error('td.when', "No test double invocation call detected for `when()`.\n\n Usage:\n when(myTestDouble('foo')).thenReturn('bar')");
log_1.default.error('td.when', `\
No test double invocation call detected for \`when()\`.
Usage:
when(myTestDouble('foo')).thenReturn('bar')\
`);
}
}
exports.default = ensureRehearsal;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ensure_rehearsal_1 = require("./ensure-rehearsal");
var chain_stubbing_1 = require("./chain-stubbing");
var add_implied_callback_arg_if_necessary_1 = require("./add-implied-callback-arg-if-necessary");
var call_log_1 = require("../value/call-log");
var stubbing_register_1 = require("../value/stubbing-register");
var stubbing_1 = require("../value/stubbing");
exports.default = (function (__rehearseInvocationHere__, options) {
var rehearsal = call_log_1.default.instance.pop();
const ensure_rehearsal_1 = require("./ensure-rehearsal");
const chain_stubbing_1 = require("./chain-stubbing");
const add_implied_callback_arg_if_necessary_1 = require("./add-implied-callback-arg-if-necessary");
const call_log_1 = require("../value/call-log");
const stubbing_register_1 = require("../value/stubbing-register");
const stubbing_1 = require("../value/stubbing");
exports.default = (__rehearseInvocationHere__, options) => {
const rehearsal = call_log_1.default.instance.pop();
ensure_rehearsal_1.default(rehearsal);
return chain_stubbing_1.default(rehearsal.double, function (type, outcomes) {
return chain_stubbing_1.default(rehearsal.double, (type, outcomes) => {
stubbing_register_1.default.instance.add(rehearsal.double, new stubbing_1.default(type, add_implied_callback_arg_if_necessary_1.default(type, rehearsal.call.args), outcomes, options));
});
});
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var assign = require("lodash/assign");
var capitalize = require("lodash/capitalize");
var clone = require("lodash/clone");
var cloneDeep = require("lodash/cloneDeep");
var cloneDeepWith = require("lodash/cloneDeepWith");
var compact = require("lodash/compact");
var defer = require("lodash/defer");
var delay = require("lodash/delay");
var each = require("lodash/each");
var every = require("lodash/every");
var extend = require("lodash/extend");
var filter = require("lodash/filter");
var find = require("lodash/find");
var findLast = require("lodash/findLast");
var get = require("lodash/get");
var groupBy = require("lodash/groupBy");
var includes = require("lodash/includes");
var invoke = require("lodash/invoke");
var isArguments = require("lodash/isArguments");
var isArray = require("lodash/isArray");
var isBoolean = require("lodash/isBoolean");
var isEmpty = require("lodash/isEmpty");
var isEqual = require("lodash/isEqual");
var isEqualWith = require("lodash/isEqualWith");
var isFunction = require("lodash/isFunction");
var isNumber = require("lodash/isNumber");
var isObject = require("lodash/isObject");
var isObjectLike = require("lodash/isObjectLike");
var isRegExp = require("lodash/isRegExp");
var isString = require("lodash/isString");
var keys = require("lodash/keys");
var last = require("lodash/last");
var map = require("lodash/map");
var reduce = require("lodash/reduce");
var reject = require("lodash/reject");
var some = require("lodash/some");
var tap = require("lodash/tap");
var toArray = require("lodash/toArray");
var transform = require("lodash/transform");
const assign = require("lodash/assign");
const capitalize = require("lodash/capitalize");
const clone = require("lodash/clone");
const cloneDeep = require("lodash/cloneDeep");
const cloneDeepWith = require("lodash/cloneDeepWith");
const compact = require("lodash/compact");
const defer = require("lodash/defer");
const delay = require("lodash/delay");
const each = require("lodash/each");
const every = require("lodash/every");
const extend = require("lodash/extend");
const filter = require("lodash/filter");
const find = require("lodash/find");
const findLast = require("lodash/findLast");
const get = require("lodash/get");
const groupBy = require("lodash/groupBy");
const includes = require("lodash/includes");
const invoke = require("lodash/invoke");
const isArguments = require("lodash/isArguments");
const isArray = require("lodash/isArray");
const isBoolean = require("lodash/isBoolean");
const isEmpty = require("lodash/isEmpty");
const isEqual = require("lodash/isEqual");
const isEqualWith = require("lodash/isEqualWith");
const isFunction = require("lodash/isFunction");
const isNumber = require("lodash/isNumber");
const isObject = require("lodash/isObject");
const isObjectLike = require("lodash/isObjectLike");
const isRegExp = require("lodash/isRegExp");
const isString = require("lodash/isString");
const keys = require("lodash/keys");
const last = require("lodash/last");
const map = require("lodash/map");
const reduce = require("lodash/reduce");
const reject = require("lodash/reject");
const some = require("lodash/some");
const tap = require("lodash/tap");
const toArray = require("lodash/toArray");
const transform = require("lodash/transform");
exports.default = {
assign: assign,
capitalize: capitalize,
clone: clone,
cloneDeep: cloneDeep,
cloneDeepWith: cloneDeepWith,
compact: compact,
defer: defer,
delay: delay,
each: each,
every: every,
extend: extend,
filter: filter,
find: find,
findLast: findLast,
get: get,
groupBy: groupBy,
includes: includes,
invoke: invoke,
isArguments: isArguments,
isArray: isArray,
isBoolean: isBoolean,
isEmpty: isEmpty,
isEqual: isEqual,
isEqualWith: isEqualWith,
isFunction: isFunction,
isNumber: isNumber,
isObject: isObject,
isObjectLike: isObjectLike,
isRegExp: isRegExp,
isString: isString,
keys: keys,
last: last,
map: map,
reduce: reduce,
reject: reject,
some: some,
tap: tap,
toArray: toArray,
transform: transform
assign,
capitalize,
clone,
cloneDeep,
cloneDeepWith,
compact,
defer,
delay,
each,
every,
extend,
filter,
find,
findLast,
get,
groupBy,
includes,
invoke,
isArguments,
isArray,
isBoolean,
isEmpty,
isEqual,
isEqualWith,
isFunction,
isNumber,
isObject,
isObjectLike,
isRegExp,
isString,
keys,
last,
map,
reduce,
reject,
some,
tap,
toArray,
transform
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("./lodash");
const lodash_1 = require("./lodash");
function proxySafeCloneDeepWith(thing, callback) {
return lodash_1.default.cloneDeepWith(thing, function (val, key, obj, stack) {
return lodash_1.default.cloneDeepWith(thing, (val, key, obj, stack) => {
if (isSafeWithProxy(key)) {

@@ -7,0 +7,0 @@ return callback(val, key, obj, stack);

{
"name": "testdouble",
"version": "3.14.0",
"version": "3.15.0",
"description": "A minimal test double library for TDD with JavaScript",

@@ -12,2 +12,9 @@ "homepage": "https://github.com/testdouble/testdouble.js",

"main": "lib/index.js",
"exports": {
".": {
"require": "./lib/index.js",
"import": "./lib/index.mjs"
},
"./": "./"
},
"files": [

@@ -26,6 +33,7 @@ "src",

"postclean": "mkdirp dist",
"compile:browser": "cross-conf-env browserify src/index.js --standalone td --outfile $npm_package_config_build_file -p tsify -p headerify",
"compile:browser": "cross-conf-env browserify src/index.js --standalone td --outfile $npm_package_config_build_file -p [ tsify --project tsconfig-browser.json ] -p headerify",
"compile:node": "tsc",
"compile:esm": "cp src/index.mjs lib/index.mjs",
"precompile": "npm run clean",
"compile": "run-s compile:node compile:browser",
"compile": "run-s compile:node compile:browser compile:esm",
"cover": "nyc --reporter=lcov --reporter=text-summary --reporter=html npm test",

@@ -37,8 +45,9 @@ "cover:report": "codeclimate-test-reporter < coverage/lcov.info",

"style:ts": "standard --fix --parser @typescript-eslint/parser --plugin @typescript-eslint/eslint-plugin \"**/*.ts\"",
"test": "teenytest --helper test/helper.js \"test/**/*.test.{js,ts}\"",
"test:all": "run-s test test:example",
"test": "run-s test:unit test:safe test:esm test:no-loader-esm test:example",
"test:unit": "teenytest --helper test/helper.js \"test/unit/**/*.test.{js,ts}\"",
"test:safe": "teenytest --helper test/helper.js \"test/safe/**/*.test.{js,ts}\"",
"test:ci": "npm run compile && run-p style test:all && echo \"All done!\"",
"test:example": "run-p test:example:babel test:example:jest test:example:jest-broken test:example:plain-html test:example:node test:example:node-ava test:example:webpack",
"test:esm": "if node test/supports-esm.js; then NODE_OPTIONS='--loader=quibble' TS_NODE_IGNORE='(?:^|/)node_modules/,notypescript' ./test/safe-esm/teenytest-proxy.js --helper test/helper.js test/safe-esm/replace.test.js; fi",
"test:no-loader-esm": "if node test/supports-esm.js; then TS_NODE_IGNORE='(?:^|/)node_modules/,notypescript' teenytest test/helper.js './test/safe-esm/*.no-loader-test.{mjs,js}'; fi",
"test:ci": "npm run compile && run-p style test && echo \"All done!\"",
"test:example": "run-p test:example:babel test:example:jest test:example:jest-broken test:example:plain-html test:example:node test:example:node-ava test:example:webpack test:example:node-esm",
"test:example:babel": "./script/run-examples babel",

@@ -50,2 +59,3 @@ "test:example:jest": "./script/run-examples jest",

"test:example:node-ava": "./script/run-examples node-ava",
"test:example:node-esm": "if node test/supports-esm.js; then ./script/run-examples node-esm; fi",
"test:example:webpack": "./script/run-examples webpack",

@@ -85,3 +95,4 @@ "version:write": "echo \"export default '$npm_package_version'\" > src/version.js",

"plugins": [
"test/support/tdify-plugin.js"
"test/support/tdify-plugin.js",
"teenytest-promise"
]

@@ -91,3 +102,3 @@ },

"lodash": "^4.17.15",
"quibble": "^0.5.7",
"quibble": "^0.6.3",
"stringify-object-es5": "^2.5.0",

@@ -106,2 +117,3 @@ "theredoc": "^1.0.0"

"is-number": "^7.0.0",
"is-promise": "^4.0.0",
"mkdirp": "^1.0.3",

@@ -112,5 +124,6 @@ "npm-run-all": "^4.1.5",

"standard": "^14.3.1",
"teenytest": "^5.3.0",
"teenytest": "^6.0.2",
"teenytest-promise": "^1.0.0",
"testdouble": "^3.12.5",
"ts-node": "^8.6.2",
"ts-node": "^8.10.1",
"tsify": "^4.0.1",

@@ -117,0 +130,0 @@ "typescript": "^3.8.2"

@@ -78,3 +78,3 @@ # testdouble.js (AKA td.js)

### `td.replace()` for replacing dependencies
### `td.replace()` and `td.replaceEsm()` for replacing dependencies

@@ -93,2 +93,6 @@ The first thing a test double library needs to do is give you a way to replace

Additionally, if you're using Node 13 or newer, you can specify testdouble as a
module loader and replace native ES modules with `td.replaceEsm()`. More details
[here](docs/7-replacing-dependencies.md#how-module-replacement-works-for-es-modules-using-import).
#### Module replacement with Node.js

@@ -154,4 +158,5 @@

If your modules are written in the ES module syntax and they specify default
exports (e.g. `export default function loadsPurchases()`), just remember that
you'll need to reference `.default` when translating to the CJS module format.
exports (e.g. `export default function loadsPurchases()`), but are actually
transpiled to CommonJS, just remember that you'll need to reference `.default`
when translating to the CJS module format.

@@ -271,5 +276,5 @@ That means instead of this:

[td.explain()](/docs/9-debugging.md#tdexplainsometestdouble)
* **`td.func<Type>()`** - returns a test double function imitating the passed type.
* **`td.func<Type>()`** - returns a test double function imitating the passed type.
Examples and more details can be found in [using with TypeScript](/docs/10-using-with-typescript.md)
#### `td.object()`

@@ -295,6 +300,6 @@

found in [our full docs](/docs/4-creating-test-doubles.md#objectobjectname)
* **`td.object<Interface>()`** - returns an object with methods exposed as test doubles
that are typed according to the passed interface. Examples and more details can be found in
* **`td.object<Interface>()`** - returns an object with methods exposed as test doubles
that are typed according to the passed interface. Examples and more details can be found in
[using with TypeScript](/docs/10-using-with-typescript.md)
#### `td.constructor()`

@@ -301,0 +306,0 @@

@@ -8,3 +8,3 @@ import tdFunction from './function'

import matchers from './matchers'
import replace from './replace'
import replace, { replaceEsm } from './replace'
import explain from './explain'

@@ -27,2 +27,3 @@ import reset from './reset'

replace,
replaceEsm,
explain,

@@ -29,0 +30,0 @@ reset,

import _ from '../wrap/lodash'
import * as quibble from 'quibble'
import replaceModule from './module'
import replaceModule, { replaceEsModule } from './module'
import replaceProperty from './property'

@@ -15,1 +15,10 @@

}
export function replaceEsm (_modulePath, _namedExportReplacement, _defaultExportReplacement) {
if (!quibble.isLoaderLoaded()) {
throw new Error('testdouble ESM loader not loaded. You cannot replace ES modules without a loader. Run node with `--loader=testdouble`.')
}
// Sending arguments instead of the above arguments is crucial because `replaceEsModule`
// uses arguments.length to figure out what to do.
return replaceEsModule(...arguments)
}

@@ -10,3 +10,3 @@ import * as quibble from 'quibble'

export default function replaceModule (path, stub) {
export default function replaceCjsModule (path, stub) {
if (typeof jest === 'object') return jestModule(...arguments)

@@ -19,1 +19,18 @@ if (arguments.length > 1) { return quibble(path, stub) }

}
export async function replaceEsModule (path, namedExportsStub, defaultExportStub) {
if (typeof jest === 'object') {
throw new Error(`stubbing ES modules (${path}) under Jest is not yet supported`)
}
if (arguments.length > 1) {
return quibble.esm(path, namedExportsStub, defaultExportStub)
}
const { modulePath, module } = await quibble.esmImportWithPath(path)
const { default: fakeDefaultExport = undefined, ...fakeNamedExports } =
imitate(module, fakeName(path, module))
await quibble.esm(modulePath, fakeNamedExports, fakeDefaultExport)
return { default: fakeDefaultExport, ...fakeNamedExports }
}

@@ -1,1 +0,1 @@

export default '3.14.0'
export default '3.15.0'

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc