Skip to content

Instantly share code, notes, and snippets.

@Logiraptor
Created August 28, 2017 21:38
Show Gist options
  • Select an option

  • Save Logiraptor/ae882a4117951693ee400f9249770ec6 to your computer and use it in GitHub Desktop.

Select an option

Save Logiraptor/ae882a4117951693ee400f9249770ec6 to your computer and use it in GitHub Desktop.
import * as sinon from "sinon";
import { Observable } from "../../lib/Rx";
export function doNothing<T>(): T {
const handler = {
get(target, name) {
return () => {};
},
};
return new Proxy({}, handler);
}
export type Spy<T> = { [K in keyof T]: sinon.SinonSpy };
export function makeSpy<T>(spies: Array<keyof T>): Spy<T> {
const result: Partial<Spy<T>> = {};
for (const name of spies) {
result[name] = sinon.spy();
}
return result as Spy<T>;
}
export function proxied(x) {
const handler = {
get(target, name) {
if (name in target) {
return target[name];
}
throw new Error(`Called ${name} unexpectedly`);
},
};
return new Proxy(x, handler);
}
export function partialMock<T>(inner: Partial<T>): T {
return proxied(inner);
}
// Capture will yield consecutive values as promises
export function capture<T>(x: Observable<T>): { readonly next: Promise<T> } {
let value: T | undefined;
let nextResolve: (x: T) => void | undefined;
x.subscribe((newVal) => {
if (typeof nextResolve !== "undefined") {
nextResolve(newVal);
value = undefined;
} else {
value = newVal;
}
});
return {
get next(): Promise<T> {
if (typeof value === "undefined") {
return new Promise((resolve) => {
nextResolve = resolve;
});
}
const resolvedVal = value;
value = undefined;
return Promise.resolve(resolvedVal);
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment