@augment-vir/test
Version:
A universal testing suite that works with Mocha style test runners _and_ Node.js's built-in test runner.
81 lines (80 loc) • 2.55 kB
JavaScript
import { wrapInTry } from '@augment-vir/common';
import { ensureError, extractErrorMessage } from '@augment-vir/core';
import { it } from './universal-it.js';
import { assertSnapshot } from './universal-snapshot.js';
/**
* Similar to `itCases` but instead of defining expectation in each test case, each test case is a
* snapshot test.
*
* In order to generate or update the snapshot files, run tests in update mode.
*
* @category Test
* @category Package : @augment-vir/test
* @example
*
* ```ts
* import {snapshotCases, describe} from '@augment-vir/test';
*
* function myFunctionToTest(a: number, b: number) {
* return a + b;
* }
*
* describe(myFunctionToTest.name, () => {
* snapshotCases(myFunctionToTest, [
* {
* it: 'handles negative numbers',
* inputs: [
* -1,
* -2,
* ],
* },
* {
* it: 'handles 0',
* inputs: [
* 0,
* 0,
* ],
* },
* {
* it: 'adds',
* inputs: [
* 3,
* 5,
* ],
* },
* ]);
* });
* ```
*
* @package [`@augment-vir/test`](https://www.npmjs.com/package/@augment-vir/test)
*/
export function snapshotCases(functionToTest, testCases) {
return testCases.map((testCase) => {
const itFunction = testCase.only ? it.only : testCase.skip ? it.skip : it;
return itFunction(testCase.it, async (testContext) => {
const functionInputs = 'input' in testCase
? [testCase.input]
: 'inputs' in testCase
? testCase.inputs
: // as cast here to cover the case where the input has NO inputs
[];
const snapshotData = await wrapInTry(async () => {
return await functionToTest(...functionInputs);
}, {
handleError(caught) {
if (testCase.fails) {
const error = ensureError(caught);
const errorClassName = error.constructor.name;
return {
[errorClassName]: extractErrorMessage(error),
};
}
else {
throw caught;
}
},
});
await assertSnapshot(testContext, snapshotData);
});
});
}