Created
September 9, 2020 06:14
-
-
Save Rwin90/dace1834ea19250ba398c9cb186afb6c to your computer and use it in GitHub Desktop.
Mock Decorator for angular service
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 {environment} from "../../../environments/environment"; | |
export type ClassConstructor = {new(...args:any[]):{}, prototype: any}; | |
export interface MockingParams<T, K> { | |
mockClass: T; | |
targetMembers: K[]; | |
force?: boolean; | |
} | |
interface AssignerParams { | |
members: (keyof any)[]; | |
source: any; | |
target: any; | |
} | |
export function Mock<T extends ClassConstructor>(params: MockingParams<T, keyof InstanceType<T>>) { | |
return function mockWith<U extends ClassConstructor>(constructor: U): U { | |
if (!isGlobalMockingEnabled() && !params.force) { return constructor; } | |
console.log('MOCK', constructor.name); | |
assignPrototypeMembers({members: params.targetMembers, source: params.mockClass, target: constructor}); | |
return constructor; | |
} | |
} | |
function isGlobalMockingEnabled() { | |
return !environment.production && (environment.mock || localStorage.getItem('mock')); | |
} | |
function assignPrototypeMembers({members, source, target}: AssignerParams) { | |
members.forEach(memberName => { | |
if (memberName in target.prototype && memberName in source.prototype) { | |
target.prototype[memberName] = source.prototype[memberName]; | |
} else { | |
throw (new Error('Method must exists in both mock class and target class.')) | |
} | |
}) | |
} | |
export function enableMockingForAllInLocalStorage() { | |
localStorage.setItem('mock', '1'); | |
} | |
export function disableMockingForAllInLocalStorage() { | |
localStorage.removeItem('mock'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment