Created
October 17, 2017 20:41
-
-
Save max-winderbaum/870da8fd5d52998070e4b68115e8dd0b to your computer and use it in GitHub Desktop.
RewirableObject
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Request, rewireRequest } from "./Request"; | |
const mockRequest = { fake: true }; | |
rewireRequest(mockRequest); | |
// Use mocked request here |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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