Created
August 16, 2023 13:20
-
-
Save kalisjoshua/1607c0128e5616ec56fa183815c2fe8c to your computer and use it in GitHub Desktop.
A tiny test "runner".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TestResult { | |
value: any | |
constructor (value: any) { | |
this.value = value | |
} | |
} | |
function assert (a: any, b?: any) { | |
throw new TestResult(b ? a === b : a) | |
} | |
function throws (fn: Function, error?: Error | string) { | |
try { | |
fn() | |
throw new TestResult(false) | |
} catch(e) { | |
throw new TestResult(error == null ? true : error == e) | |
} | |
} | |
function test (label: string, action: Function) { | |
let result = false | |
try { | |
action() | |
} catch (thrown) { | |
if (thrown instanceof TestResult) { | |
result = thrown.value | |
} else { | |
result = false | |
} | |
} | |
console.log(` ${result ? '✓' : '×'} ${label}`) | |
if (!result) console.log(`\t\t"${result}"\n`) | |
} | |
test('should pass', () => { | |
const error = new Error('testable') | |
assert(true) | |
assert(1, 1) | |
throws(() => {throw error}) | |
throws(() => {throw error}, error) | |
}) | |
test('should fail; assert false', () => { | |
assert(false) | |
}) | |
test('should fail; uncaught error', () => { | |
throw new Error('testing') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment