import type { MethodName, Options, } from './decorators'; import type { TestSuite, TestSuiteConstructor } from './test-suite'; export type TestRunnerOptions = { name?: string; only?: boolean; skip?: boolean; }; type TestMethod = (...args: unknown[]) => Promise; export class TestRunner { public static run( suiteConstructor: TestSuiteConstructor, options: TestRunnerOptions = {}, ): void { const suite = new suiteConstructor(); const { name = suite.constructor.name } = options; const describeFunction = this.getDescribeFunction(options); describeFunction(name, this.describe.bind(this, suite)); } private static getDescribeFunction(options: TestRunnerOptions = {}): jest.Describe { const { only = false, skip = false, } = options; let describeFunction = describe; if (only) { describeFunction = describeFunction.only; } if (skip) { describeFunction = describeFunction.skip; } return describeFunction; } private static describe(suite: TestSuite): void { beforeAll(async() => suite.setUp()); afterAll(async() => suite.tearDown()); beforeEach(async() => suite.beforeEach()); afterEach(async() => suite.afterEach()); if (!suite.testsMap) { suite.testsMap = new Map(); } suite.testsMap.forEach((options, methodName) => this.registerTests(suite, options, methodName)); } private static registerTests(suite: TestSuite, options: Options, testName: MethodName): void { const { name = testName.toString(), timeout, } = options; if (options.todo) { test.todo(name); return; } const method = this.getTestMethod(suite, testName); const registerMethod = this.getTestRegisterMethod(options); registerMethod(name, method, timeout); } private static getTestMethod(suite: TestSuite, methodName: MethodName): TestMethod { const testMethod = ((suite as any)[methodName] as (...args: unknown[]) => Promise).bind(suite); return async(...args: any[]): Promise => testMethod(...args); } private static getTestRegisterMethod(options: Options): jest.It { let registerMethod = test; if (options.concurrent) { registerMethod = registerMethod.concurrent; } if (options.skip) { registerMethod = registerMethod.skip; } if (options.only) { registerMethod = registerMethod.only; } if (options.each) { registerMethod = registerMethod.each(options.each) as jest.It; } return registerMethod; } }