Skip to content

Instantly share code, notes, and snippets.

@soundyogi
Last active December 6, 2016 20:42
Show Gist options
  • Save soundyogi/8ad08368f0509df5667d9eeef7e1f842 to your computer and use it in GitHub Desktop.
Save soundyogi/8ad08368f0509df5667d9eeef7e1f842 to your computer and use it in GitHub Desktop.
Vanilla JavaScript Test Harness Implementations for Fun and Profit. Never leave the house without one!
// I like to start projects with a harness, so here is an async and a non-async harness
// compatible* to the tape api so they are easily portable
//
// *theres just 2 methods I normally use but you can add as many as you like
//
function test(name, f){
test.run = test.run || false
test.queue = test.queue || []
test.queue.push(() => {
console.log(`Test: %c${name}`, 'color: violet')
f({ end, ok })
})
if(test.run) return
test.run = true
setTimeout(end, 0) //wait until stack empty - so all tests have been added to queue
/* Implement as many Tape Features as you like:
*/
function end(){
if(test.queue.length !== 0){ return test.queue.shift()() }
test.run = false
console.log("done.")
}
function ok(expr, msg){
expr
? console.log(`%c:) pass: ${msg}`, 'color: darkgreen')
: console.log(`%c:( fail: ${msg}`, 'color: red')
}
}
test("init", function(t){
t.ok(true, "okgo")
t.end()
})
test("async test", function(t){
setTimeout(function(){
t.ok(true, "i am async")
t.end()
}, 2000)
})
test("async test", function(t){
setTimeout(function(){
t.ok(true, "i am also async")
t.end()
}, 1000)
})
test("selftest after async", function(t){
t.ok(true, "I pass")
t.ok(false, " I fail :( ")
t.end()
})
function test(msg, f){
console.log(`Test: %c${msg}`, 'color: violet')
f({ end, ok })
/* Tape Api */
function end(){} //noop
function ok(expr, msg){
expr
? console.log(`%c:) pass: ${msg}`, 'color: darkgreen')
: console.log(`%c:( fail: ${msg}`, 'color: red')
}
}
test("the truth", t => {
t.ok(true, "I am true")
t.ok(false, "I am false")
t.end()
})
test("some math", t => {
t.ok(Math.sqrt(16) === 4, "root of 16 is 4")
t.ok(fetch instanceof Function, "fetch is cool")
t.end()
})
// I use this really simple one for throwaway testing or testing legacy js while in the devtools
const log = (...msg) => console.log(...msg)
const test = function t(expr, msg){
expr ? log('%c!pass:'+msg, 'color:green') : log('%c?fail:'+msg, 'color:red')
}
test(true, 'selftest pass')
test(false, 'selftest fail')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment