Skip to content

Commit

Permalink
feat: onTestFail hook (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber committed Oct 31, 2022
1 parent aa70cc6 commit 3b8c2ff
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
22 changes: 19 additions & 3 deletions src/create-test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { green, red } from 'kleur/colors'; // eslint-disable-line node/file-extension-in-import
import type { Test, PendingTests } from './types';
import type {
Test,
TestApi,
onTestFailCallback,
PendingTests,
} from './types';

const successIcon = green('✔');
const failureIcon = red('✖');
Expand Down Expand Up @@ -27,19 +32,26 @@ export function createTest(
}

const testRunning = (async () => {
let onTestFail: undefined | onTestFailCallback;
const api: TestApi = {
onTestFail(callback) {
onTestFail = callback;
},
};

try {
if (timeout) {
const controller = { timeoutId: undefined };
try {
await Promise.race([
testFunction(),
testFunction(api),
throwOnTimeout(timeout, controller),
]);
} finally {
clearTimeout(controller.timeoutId);
}
} else {
await testFunction();
await testFunction(api);
}

console.log(successIcon, title);
Expand All @@ -58,6 +70,10 @@ export function createTest(

console.error(error);
process.exitCode = 1;

if (typeof onTestFail === 'function') {
onTestFail(error);
}
}
})();

Expand Down
8 changes: 7 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,15 @@ type RunTestSuite = <
...args: InferCallback<Callback>['args']
) => InferCallback<Callback>['returnType'];

export type onTestFailCallback = (error: Error) => void;

export type TestApi = {
onTestFail: (callback: onTestFailCallback) => void;
};

export type Test = (
title: string,
testFunction: () => void,
testFunction: (api: TestApi) => void,
timeout?: number,
) => Promise<void>;

Expand Down

0 comments on commit 3b8c2ff

Please sign in to comment.