All files / src/promises assert.ts

100% Statements 4/4
100% Branches 4/4
100% Functions 1/1
100% Lines 3/3

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                  6x   6x   4x                                    
/**
 * Ensures a promise matches the given predicate
 * @returns The original promise
 */
export async function assert<P extends Promise<any>, V = P extends Promise<infer V> ? V : never>(
  p: P,
  predicate: (value: V) => boolean,
  message?: string
): Promise<V> {
  const value: V = await p;
 
  if (predicate(value)) return value;
 
  throw new Error(message ?? 'Value does not satisfy predicate');
}
 
/* c8 ignore start */
export namespace assert {
  /* c8 ignore end */
 
  /**
   * Ensures a promise result is defined
   * @returns The original promise
   */
  export async function defined<P extends Promise<any>, V = Awaited<P>>(
    p: P,
    message?: string
  ): Promise<Exclude<V, undefined | null>> {
    return assert(p, (v) => v !== undefined && v !== null, message);
  }
}