|
| 1 | +import type { ContextStepFunction, SimpleStepFunction, StepOptions, StepSubject, TestContext, TestSubject, WrappedTestOptions } from "../mod.ts"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Browser test runner - a minimal test runner for browser environments. |
| 5 | + * Results are logged to the console with styled output where supported. |
| 6 | + */ |
| 7 | + |
| 8 | +// Track test results for summary |
| 9 | +const testResults: Array<{ name: string; passed: boolean; error?: Error; duration: number }> = []; |
| 10 | + |
| 11 | +// Check if console supports styling (most modern browsers do) |
| 12 | +const supportsStyles = typeof window !== "undefined" && typeof console !== "undefined"; |
| 13 | + |
| 14 | +// Console styling for browser DevTools |
| 15 | +const styles = { |
| 16 | + pass: "color: #22c55e; font-weight: bold", |
| 17 | + fail: "color: #ef4444; font-weight: bold", |
| 18 | + skip: "color: #f59e0b; font-weight: bold", |
| 19 | + step: "color: #6366f1", |
| 20 | + info: "color: #64748b", |
| 21 | +}; |
| 22 | + |
| 23 | +function logResult(type: "pass" | "fail" | "skip" | "step" | "info", message: string): void { |
| 24 | + if (supportsStyles) { |
| 25 | + console.log(`%c${message}`, styles[type]); |
| 26 | + } else { |
| 27 | + console.log(message); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +export async function wrappedTest( |
| 32 | + name: string, |
| 33 | + testFn: TestSubject, |
| 34 | + options: WrappedTestOptions, |
| 35 | +): Promise<void> { |
| 36 | + // Handle skip option |
| 37 | + if (options?.skip) { |
| 38 | + logResult("skip", `⊘ SKIP: ${name}`); |
| 39 | + testResults.push({ name, passed: true, duration: 0 }); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + const startTime = performance.now(); |
| 44 | + |
| 45 | + // Create wrapped context with step method |
| 46 | + const wrappedContext: TestContext = { |
| 47 | + // deno-lint-ignore no-explicit-any |
| 48 | + step: async (_stepName: string, stepFn: SimpleStepFunction | ContextStepFunction | StepSubject, stepOptions?: StepOptions): Promise<any> => { |
| 49 | + // Browser doesn't have native nested test support, so we run steps inline |
| 50 | + // Check function arity to determine how to handle it: |
| 51 | + // - length 0: Simple function with no parameters |
| 52 | + // - length 1: Function with context parameter for nesting |
| 53 | + // - length 2: Function with context and done callback |
| 54 | + const isSimpleFunction = stepFn.length === 0; |
| 55 | + const isContextFunction = stepFn.length === 1 && !stepOptions?.waitForCallback; |
| 56 | + const isCallbackFunction = stepOptions?.waitForCallback === true; |
| 57 | + |
| 58 | + const stepStart = performance.now(); |
| 59 | + |
| 60 | + try { |
| 61 | + if (isSimpleFunction && !isCallbackFunction) { |
| 62 | + // Simple function without context or callback |
| 63 | + await (stepFn as SimpleStepFunction)(); |
| 64 | + } else if (isContextFunction) { |
| 65 | + // Function with context parameter - create proper nested context |
| 66 | + const nestedWrappedContext: TestContext = createNestedContext(); |
| 67 | + await (stepFn as (context: TestContext) => void | Promise<void>)(nestedWrappedContext); |
| 68 | + } else { |
| 69 | + // Callback-based function |
| 70 | + const nestedWrappedContext: TestContext = createNestedContext(); |
| 71 | + let stepFnPromise = undefined; |
| 72 | + const stepCallbackPromise = new Promise((resolve, reject) => { |
| 73 | + stepFnPromise = (stepFn as StepSubject)(nestedWrappedContext, (e) => { |
| 74 | + if (e) reject(e); |
| 75 | + else resolve(0); |
| 76 | + }); |
| 77 | + }); |
| 78 | + if (stepOptions?.waitForCallback) await stepCallbackPromise; |
| 79 | + await stepFnPromise; |
| 80 | + } |
| 81 | + |
| 82 | + const stepDuration = performance.now() - stepStart; |
| 83 | + logResult("step", ` ✓ ${_stepName} (${stepDuration.toFixed(0)}ms)`); |
| 84 | + } catch (error) { |
| 85 | + const stepDuration = performance.now() - stepStart; |
| 86 | + logResult("fail", ` ✗ ${_stepName} (${stepDuration.toFixed(0)}ms)`); |
| 87 | + throw error; |
| 88 | + } |
| 89 | + }, |
| 90 | + }; |
| 91 | + |
| 92 | + // Helper function to create nested context with proper step support |
| 93 | + function createNestedContext(): TestContext { |
| 94 | + return { |
| 95 | + // deno-lint-ignore no-explicit-any |
| 96 | + step: async (_nestedStepName: string, nestedStepFn: SimpleStepFunction | ContextStepFunction | StepSubject, nestedStepOptions?: StepOptions): Promise<any> => { |
| 97 | + const isNestedSimple = nestedStepFn.length === 0; |
| 98 | + const isNestedContext = nestedStepFn.length === 1 && !nestedStepOptions?.waitForCallback; |
| 99 | + const isNestedCallback = nestedStepOptions?.waitForCallback === true; |
| 100 | + |
| 101 | + const stepStart = performance.now(); |
| 102 | + |
| 103 | + try { |
| 104 | + if (isNestedSimple && !isNestedCallback) { |
| 105 | + await (nestedStepFn as SimpleStepFunction)(); |
| 106 | + } else if (isNestedContext) { |
| 107 | + // Recursive: create another level of nesting |
| 108 | + const deeperWrappedContext = createNestedContext(); |
| 109 | + await (nestedStepFn as (context: TestContext) => void | Promise<void>)(deeperWrappedContext); |
| 110 | + } else { |
| 111 | + // Callback-based nested step |
| 112 | + const deeperWrappedContext = createNestedContext(); |
| 113 | + let nestedStepFnPromise = undefined; |
| 114 | + const nestedCallbackPromise = new Promise((resolve, reject) => { |
| 115 | + nestedStepFnPromise = (nestedStepFn as StepSubject)(deeperWrappedContext, (e) => { |
| 116 | + if (e) reject(e); |
| 117 | + else resolve(0); |
| 118 | + }); |
| 119 | + }); |
| 120 | + if (nestedStepOptions?.waitForCallback) await nestedCallbackPromise; |
| 121 | + await nestedStepFnPromise; |
| 122 | + } |
| 123 | + |
| 124 | + const stepDuration = performance.now() - stepStart; |
| 125 | + logResult("step", ` ✓ ${_nestedStepName} (${stepDuration.toFixed(0)}ms)`); |
| 126 | + } catch (error) { |
| 127 | + const stepDuration = performance.now() - stepStart; |
| 128 | + logResult("fail", ` ✗ ${_nestedStepName} (${stepDuration.toFixed(0)}ms)`); |
| 129 | + throw error; |
| 130 | + } |
| 131 | + }, |
| 132 | + }; |
| 133 | + } |
| 134 | + |
| 135 | + try { |
| 136 | + // Adapt the context here |
| 137 | + let testFnPromise = undefined; |
| 138 | + const callbackPromise = new Promise((resolve, reject) => { |
| 139 | + testFnPromise = testFn(wrappedContext, (e) => { |
| 140 | + if (e) reject(e); |
| 141 | + else resolve(0); |
| 142 | + }); |
| 143 | + }); |
| 144 | + let timeoutId: ReturnType<typeof setTimeout> | undefined; |
| 145 | + try { |
| 146 | + if (options.timeout) { |
| 147 | + const timeoutPromise = new Promise((_, reject) => { |
| 148 | + timeoutId = setTimeout(() => { |
| 149 | + reject(new Error("Test timed out")); |
| 150 | + }, options.timeout); |
| 151 | + }); |
| 152 | + await Promise.race([options.waitForCallback ? callbackPromise : testFnPromise, timeoutPromise]); |
| 153 | + } else { |
| 154 | + await options.waitForCallback ? callbackPromise : testFnPromise; |
| 155 | + } |
| 156 | + } finally { |
| 157 | + if (timeoutId) clearTimeout(timeoutId); |
| 158 | + // Make sure testFnPromise has completed |
| 159 | + await testFnPromise; |
| 160 | + if (options.waitForCallback) await callbackPromise; |
| 161 | + } |
| 162 | + |
| 163 | + const duration = performance.now() - startTime; |
| 164 | + logResult("pass", `✓ PASS: ${name} (${duration.toFixed(0)}ms)`); |
| 165 | + testResults.push({ name, passed: true, duration }); |
| 166 | + } catch (error) { |
| 167 | + const duration = performance.now() - startTime; |
| 168 | + logResult("fail", `✗ FAIL: ${name} (${duration.toFixed(0)}ms)`); |
| 169 | + if (error instanceof Error) { |
| 170 | + console.error(` Error: ${error.message}`); |
| 171 | + if (error.stack) { |
| 172 | + console.error(` Stack: ${error.stack}`); |
| 173 | + } |
| 174 | + testResults.push({ name, passed: false, error, duration }); |
| 175 | + } else { |
| 176 | + console.error(` Error: ${String(error)}`); |
| 177 | + testResults.push({ name, passed: false, error: new Error(String(error)), duration }); |
| 178 | + } |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +/** |
| 183 | + * Get a summary of all test results. |
| 184 | + * Useful for integrating with CI systems or custom reporting. |
| 185 | + */ |
| 186 | +export function getTestResults(): Array<{ name: string; passed: boolean; error?: Error; duration: number }> { |
| 187 | + return [...testResults]; |
| 188 | +} |
| 189 | + |
| 190 | +/** |
| 191 | + * Print a summary of all test results. |
| 192 | + * Call this at the end of your test file to see the overall results. |
| 193 | + */ |
| 194 | +export function printTestSummary(): void { |
| 195 | + const passed = testResults.filter((r) => r.passed).length; |
| 196 | + const failed = testResults.filter((r) => !r.passed).length; |
| 197 | + const total = testResults.length; |
| 198 | + const totalDuration = testResults.reduce((acc, r) => acc + r.duration, 0); |
| 199 | + |
| 200 | + console.log("\n" + "=".repeat(50)); |
| 201 | + logResult("info", `Test Summary: ${passed}/${total} passed, ${failed} failed (${totalDuration.toFixed(0)}ms)`); |
| 202 | + |
| 203 | + if (failed > 0) { |
| 204 | + console.log("\nFailed tests:"); |
| 205 | + testResults.filter((r) => !r.passed).forEach((r) => { |
| 206 | + logResult("fail", ` ✗ ${r.name}`); |
| 207 | + if (r.error) { |
| 208 | + console.error(` ${r.error.message}`); |
| 209 | + } |
| 210 | + }); |
| 211 | + } |
| 212 | +} |
0 commit comments