Skip to content

Instantly share code, notes, and snippets.

@kalisjoshua
Created August 16, 2023 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalisjoshua/1607c0128e5616ec56fa183815c2fe8c to your computer and use it in GitHub Desktop.
Save kalisjoshua/1607c0128e5616ec56fa183815c2fe8c to your computer and use it in GitHub Desktop.
A tiny test "runner".
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