All files / blueprint blueprint.ts

100% Statements 13/13
100% Branches 2/2
100% Functions 4/4
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571x                                                     1x         1x 4x           1x 13x 13x 1x     12x           1x 1x   10x    
import { generate } from "../generate/mock";
 
type Closure = () => unknown;
/**
 * Blueprint for a model to mock. Use the key-names of the type and value must be a string (eg. the type to generate)
 *
 * Example:
 * ```
 * export interface A {
 *   a: number;
 *   b: string;
 *   c: Date;
 * }
 * const bp: Blueprint<A> = {
 *   a: 'number', // ok
 *   b: 'guid',   // ok
 *   d: 'string'  // => error: no such property on interface A
 * }
 * ```
 */
export type Blueprint<T> = {
  [P in keyof T]?: ReturnType<Closure>;
};
 
/**
 * Registry with all the blueprints in it
 */
const registry = new Map<string, Blueprint<unknown>>();
 
/**
 * Generate a mock
 */
export function register<T>(name: string, blueprint: Blueprint<T>): void {
  registry.set(name, blueprint);
}
 
/**
 * Returns a mock from a previously registered `Blueprint`
 */
export function from<T>(name: string): T {
  const blueprint = registry.get(name);
  if (!blueprint) {
    throw new Error(`Cannot find blueprint for name ${name}`);
  }
 
  return generate<T>(blueprint);
}
 
/**
 * Returns an array of mocks from a previously registered `Blueprint`
 */
export function arrayFrom<T>(name: string, length: number): T[] {
  const ar = new Array(length).fill(0);
 
  return ar.map(() => from(name));
}