Skip to content

Instantly share code, notes, and snippets.

@lydemann
Last active February 20, 2020 09:31
Show Gist options
  • Save lydemann/f94c36147fc232851824e6421ce0a98f to your computer and use it in GitHub Desktop.
Save lydemann/f94c36147fc232851824e6421ce0a98f to your computer and use it in GitHub Desktop.
Spy helper for mocking out services.
import { Provider, Type } from '@angular/core';
export type Mock<T> = T & { [P in keyof T]: T[P] & jasmine.Spy };
export function createMagicalMock<T>(type: Type<T>): Mock<T> {
const target: any = {};
function installProtoMethods(proto: any) {
if (proto === null || proto === Object.prototype) {
return;
}
for (const key of Object.getOwnPropertyNames(proto)) {
// tslint:disable-next-line: no-non-null-assertion
const descriptor = Object.getOwnPropertyDescriptor(proto, key)!;
if (typeof descriptor.value === 'function' && key !== 'constructor') {
target[key] = jasmine.createSpy(key);
}
}
installProtoMethods(Object.getPrototypeOf(proto));
}
installProtoMethods(type.prototype);
return target;
}
export function provideMagicalMock<T>(type: Type<T>): Provider {
return {
provide: type,
useFactory: () => createMagicalMock(type)
};
}
@MaksymRybak
Copy link

VERY GOOD! NICE HELPER! THX!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment