Skip to content

Instantly share code, notes, and snippets.

@bhrott
Last active May 9, 2018 15:35
Show Gist options
  • Save bhrott/a37a9e96e17e9fc05fae61b1d05d2fc7 to your computer and use it in GitHub Desktop.
Save bhrott/a37a9e96e17e9fc05fae61b1d05d2fc7 to your computer and use it in GitHub Desktop.
Javascript: Stormbreaker Test Lib

Stormbreaker (ultra simple test api for js in the browser)

Instalation

Just add the javascript to your html =).

<script src="stormbreaker.js"></script>

Usage

test('my test 1', assert => {
	assert.equals(valueA, valueB)
})

test('my test 2', assert => {
	assert.isTrue(value)
})

test('my test 3', assert => {
	assert.isFalse(value)
})

test('my test 4', assert => {
	assert.throwsWithMessage(MyErrorClass, 'my error message', () => {
        // my code that raises an error.
	})
})

test('my test 5', assert => {
	assert.throws(MyErrorClass, () => {
        // my code that raises an error.
	})
})

Results

The results will be outputed in developer console.

class TestAssertionFailedError extends Error {
constructor(message) {
super(message)
}
}
class TestAssertion {
equals(expected, obtained) {
if (expected !== obtained) {
throw new TestAssertionFailedError(`expected: ${expected}, obtained: ${obtained}`)
}
}
isTrue(obtained) {
if (obtained !== true) {
throw new TestAssertionFailedError(`expected: true, obtained: ${obtained}`)
}
}
isFalse(obtained) {
if (obtained !== false) {
throw new TestAssertionFailedError(`expected: false, obtained: ${obtained}`)
}
}
throws(errorClass, methodHandler) {
try {
methodHandler()
throw 'test_failed'
} catch (error) {
if (error === 'test_failed') {
throw new TestAssertionFailedError(`method not raise ${errorClass.name} error.`)
}
if (error instanceof errorClass === false) {
throw new TestAssertionFailedError(
`expected error class: ${errorClass.name}, obtainet ${
error.constructor.name
}`
)
}
return error
}
}
throwsWithMessage(errorClass, errorMessage, methodHandler) {
const errorThrowed = this.throws(errorClass, methodHandler)
if (errorThrowed.message !== errorMessage) {
throw new Error(`expected message: "${errorMessage}", obtained message: "${errorThrowed.message}"`)
}
}
}
function test(testName, testMethod) {
try {
testMethod(new TestAssertion())
console.log(`%c SUCCESS: ${testName}`, 'color: green')
} catch (error) {
console.log(`%c ERROR: ${testName} | ${error.message}`, 'color: red')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment