japa
Version:
Lean test runner for Node.js
126 lines (125 loc) • 3.59 kB
JavaScript
/**
* @module Core
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Callable = void 0;
/*
* japa
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const Exceptions_1 = require("../Exceptions");
const debug_1 = __importDefault(require("debug"));
/**
* @ignore
*/
const debug = (0, debug_1.default)('japa');
/**
* Executes the function as promise
* @ignore
*/
async function asPromise(fn, args) {
return fn(...args);
}
/**
* Calls a function and tracks it's completion in multiple ways. If original function
* relies on `done`, then it will wait for `done` to be called. Also if timeout is
* defined, the function will fail if doesn't return before the timeout.
*/
function Callable(resolveFn, callback, timeout) {
return new Promise((resolve, reject) => {
let postCallable = null;
const args = resolveFn(done, function postRun(fn) {
postCallable = fn;
});
/**
* Finding if we need to wait for done to be called
*/
const needsDone = args.length === callback.length;
debug('needsDone %s', needsDone);
/**
* Is callable completed?
*/
let completed = false;
/**
* Timer to timeout the test, if timeout is defined
*/
let timer = null;
/**
* Clears the timer if it exists
*/
function clearTimer() {
if (timer) {
debug('clearing timer');
clearTimeout(timer);
}
}
/**
* Finish the callable
*/
function finish(error) {
if (typeof (postCallable) === 'function' && !error) {
try {
postCallable(...args);
}
catch (postCallableError) {
error = postCallableError;
}
}
debug(error ? 'finishing callable as error' : 'finishing callable');
completed = true;
clearTimer();
if (error) {
reject(error);
}
else {
resolve();
}
}
/**
* Done is passed to fn to mark them as completed. When `done`
* is used, we need wait for it to be called or timeout.
*/
function done(error) {
if (completed) {
return;
}
if (error) {
finish(error);
return;
}
finish();
}
/**
* Only set the timer, when timeout is over 0
*/
if (timeout > 0) {
debug('creating timer');
timer = setTimeout(() => {
debug('timeout');
/* istanbul ignore else */
if (!completed) {
finish(new Exceptions_1.TimeoutException(`Test timeout after ${timeout} milliseconds`));
}
}, timeout);
}
debug('executing callable');
asPromise(callback, args)
.then(() => {
if (!needsDone) {
finish();
}
})
.catch((error) => {
finish(error);
});
});
}
exports.Callable = Callable;
;