sinon-typed
Version:
Nicer stubbing in a TypeScript environment
92 lines • 2.86 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const sinon = require("sinon");
class SinonTyped {
static mock(sandbox) {
return new MockImpl(sandbox);
}
static stub(sandbox) {
return new StubImpl(sandbox);
}
static partiallyStub(partial, sandbox) {
const stubT = SinonTyped.stub(sandbox);
for (const key of Object.keys(partial)) {
const typedKey = key;
const value = partial[typedKey];
if (value) {
stubT.stubProperty(typedKey).returns(value);
}
}
return stubT;
}
static partially(partial, sandbox) {
return SinonTyped.partiallyStub(partial, sandbox).object;
}
}
exports.SinonTyped = SinonTyped;
class MockImpl {
constructor(_sandbox) {
this.object = {};
if (_sandbox) {
this.control = _sandbox.mock(this.object);
}
else {
this.control = sinon.mock(this.object);
}
const expects = this.control.expects;
// creates a dummy method before mocking it.
this.control.expects = (method) => {
if (!this.object.hasOwnProperty(method)) {
createDummyMethod(this.object, method);
}
return expects.bind(this.control)(method);
};
}
}
class StubImpl {
constructor(_sandbox) {
this._sandbox = _sandbox;
this.object = {};
this.stub = {};
}
stubMethod(method) {
if (!this.stub.hasOwnProperty(method)) {
createDummyMethod(this.object, method);
this.stub[method] = this._stub(method);
}
return this.stub[method];
}
stubProperty(property) {
if (this.stub.hasOwnProperty(property)) {
this.stub[property].resetBehavior();
}
if (this._sandbox) {
const sb = this._sandbox;
return {
returns: (value) => {
this.object[property] = undefined; // tslint:disable-line:no-any
this.stub[property] = sb.stub(this.object, property).value(value);
}
};
}
else {
return {
returns: (value) => {
this.object[property] = undefined; // tslint:disable-line:no-any
this.stub[property] = sinon.stub(this.object, property);
this.stub[property].value(value);
}
};
}
}
_stub(method) {
if (this._sandbox) {
return this._sandbox.stub(this.object, method);
}
return sinon.stub(this.object, method);
}
}
function createDummyMethod(t, method) {
t[method] = (() => undefined); // tslint:disable-line:no-any
}
//# sourceMappingURL=sinon-typed.js.map