All files / src/vitest testLaw.ts

100% Statements 25/25
100% Branches 12/12
100% Functions 3/3
100% Lines 25/25

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 57  1x   1x         1x 1x 843x 762x   762x 762x   762x 756x 762x 762x                                             1x 41x 41x 4x 4x 41x 41x 41x   41x 41x 41x 41x 1x  
import type {TestAPI} from 'vitest'
import {test} from 'vitest'
import type {Law, UnknownArgs} from '../law.js'
import {asAssert} from '../law.js'
 
/**
 * @internal
 */
export const testLawWith =
  (testApi: TestAPI | (typeof test)['only']) =>
  <Ts extends UnknownArgs>(law: Law<Ts>): void => {
    const {note, parameters} = law
 
    const suffix =
      (parameters?.verbose ?? false) && note !== '' ? `: ${note}` : ''
 
    testApi(law.name + suffix, () => {
      asAssert(law)
    })
  }
 
/**
 * Attempts to find a counterexample for the single given {@link law.Law | Law}.
 *
 * Meant to be called from inside a `Vitest` test suite, perhaps inside some
 * `describe()` block, but _not_ inside a `test()`/`it()` block.
 *
 * [testLaw.skip](https://vitest.dev/api/#test-skip),
 * [testLaw.only](https://vitest.dev/api/#test-only),
 * [testLaw.skipIf](https://vitest.dev/api/#test-skipif),
 * and [testLaw.runIf](https://vitest.dev/api/#test-runif)
 * all behave just like their `vitest` counterparts.
 *
 * See also {@link law.checkLaw | checkLaw}.
 * @typeParam Ts - Tuple of types for law predicate arguments.
 * @param law - Law under test.
 * @property only - Run _only_ this law test and no other.
 * @property skip - Skip this law test.
 * @property runIf - Run this law test only if the condition holds.
 * @property skipIf - Skip this law test only if the condition holds.
 * @category vitest
 */
export const testLaw = (() => {
  return Object.assign(
    <Ts extends UnknownArgs>(law: Law<Ts>): void => {
      testLawWith(test)(law)
    },
    {
      skip: testLawWith(test.skip),
      only: testLawWith(test.only),
 
      skipIf: (condition: unknown) => testLawWith(test.skipIf(condition)),
      runIf: (condition: unknown) => testLawWith(test.runIf(condition)),
    },
  )
})()