Skip to content

Instantly share code, notes, and snippets.

@max-winderbaum
Created October 17, 2017 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-winderbaum/870da8fd5d52998070e4b68115e8dd0b to your computer and use it in GitHub Desktop.
Save max-winderbaum/870da8fd5d52998070e4b68115e8dd0b to your computer and use it in GitHub Desktop.
RewirableObject
import { Request, rewireRequest } from "./Request";
const mockRequest = { fake: true };
rewireRequest(mockRequest);
// Use mocked request here
import * as request from "request";
import { RewirableObject } from "./RewirableObject";
const rewirable = new RewirableObject(request);
export const rewireRequest = rewirable.rewire;
export type requestType = typeof request;
export const Request = rewirable.get() as requestType;
/**
* Create a proxy object that can be replaced unbeknown to external modules for testing purposes
*
* This should be used to replace side-effecty modules like Log, etc. It can be used like:
*
* import {RewirableObject} from "./RewirableObject";
*
* const rewirable = new RewirableObject(mySideEffectyObject);
* export const rewireMySideEffectyObject = rewirable.rewire;
* export const MySideEffectyObject = rewirable.get() as typeof mySideEffectyObject;
*/
export class RewirableObject {
private instance: any;
private proxyInstance: any;
constructor(instance: any) {
this.instance = instance;
const that = this;
const rewireHandler = {
get(target: any, name: string) {
return that.instance[name];
},
apply(target: any, thisArg: any, argumentsList: any) {
return that.instance.apply(thisArg, argumentsList);
},
};
this.proxyInstance = new Proxy({}, rewireHandler);
this.get = this.get.bind(this);
this.rewire = this.rewire.bind(this);
}
public get() {
return this.proxyInstance;
}
public rewire(newInstance: any) {
this.instance = newInstance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment