ts-sinon
Version:
sinon library extension to stub whole object and interfaces
90 lines (89 loc) • 3.25 kB
JavaScript
"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 });
exports.stubInterface = exports.stubConstructor = exports.stubObject = void 0;
var sinon = require("sinon");
function stubObject(object, methods) {
var stubObject = Object.assign({}, object);
var objectMethods = getObjectMethods(object);
var excludedMethods = [
'__defineGetter__', '__defineSetter__', 'hasOwnProperty',
'__lookupGetter__', '__lookupSetter__', 'propertyIsEnumerable',
'toString', 'valueOf', '__proto__', 'toLocaleString', 'isPrototypeOf'
];
for (var method in object) {
if (typeof object[method] == "function") {
objectMethods.push(method);
}
}
for (var _i = 0, objectMethods_1 = objectMethods; _i < objectMethods_1.length; _i++) {
var method = objectMethods_1[_i];
if (!excludedMethods.includes(method)) {
stubObject[method] = object[method];
}
}
if (Array.isArray(methods)) {
for (var _a = 0, methods_1 = methods; _a < methods_1.length; _a++) {
var method = methods_1[_a];
stubObject[method] = sinon.stub();
}
}
else if (typeof methods == "object") {
for (var method in methods) {
stubObject[method] = sinon.stub();
stubObject[method].returns(methods[method]);
}
}
else {
for (var _b = 0, objectMethods_2 = objectMethods; _b < objectMethods_2.length; _b++) {
var method = objectMethods_2[_b];
if (typeof object[method] == "function" && method !== "constructor") {
stubObject[method] = sinon.stub();
}
}
}
return stubObject;
}
exports.stubObject = stubObject;
function stubConstructor(constructor) {
var constructorArgs = [];
for (var _i = 1; _i < arguments.length; _i++) {
constructorArgs[_i - 1] = arguments[_i];
}
return stubObject(new (constructor.bind.apply(constructor, __spreadArrays([void 0], constructorArgs)))());
}
exports.stubConstructor = stubConstructor;
function stubInterface(methods) {
if (methods === void 0) { methods = {}; }
var object = stubObject({}, methods);
return new Proxy(object, {
get: function (target, name) {
if (!target.hasOwnProperty(name) && name !== 'then') {
target[name] = sinon.stub();
}
return target[name];
}
});
}
exports.stubInterface = stubInterface;
function getObjectMethods(object) {
var methods = [];
while ((object = Reflect.getPrototypeOf(object))) {
var keys = Reflect.ownKeys(object);
keys.forEach(function (key) {
if (typeof key === 'string') {
methods.push(key);
}
});
}
return methods;
}
sinon['stubObject'] = stubObject;
sinon['stubInterface'] = stubInterface;
exports.default = sinon;