Created
July 24, 2023 04:22
-
-
Save Grubba27/ea13eac9d144c8ec4c087c9843155a2f to your computer and use it in GitHub Desktop.
dead simple testing framework in js
This file contains 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
/** | |
* | |
* @param {string} name | |
* @param {(assert: typeof assert) => void} callback | |
*/ | |
function assement(name, callback) { | |
let counter = 0, | |
failed = 0, | |
errorList = []; | |
console.log(`Running suite: ${name}`); | |
/** | |
* @param {any} expected | |
* @param {any} actual | |
* @returns {void} | |
*/ | |
const assert = (expected, actual) => { | |
counter++; | |
// if is an array, compare the elements | |
if (Array.isArray(expected) && Array.isArray(actual)) { | |
if (expected.length !== actual.length) { | |
failed++; | |
errorList.push( | |
new Error( | |
`Expected array of length ${expected.length} but got ${actual.length}` | |
) | |
); | |
} else { | |
for (let i = 0; i < expected.length; i++) { | |
if (expected[i] !== actual[i]) { | |
failed++; | |
errorList.push( | |
new Error( | |
`Expected ${expected[i]} but got ${actual[i]} at index ${i}` | |
) | |
); | |
} | |
} | |
} | |
return; | |
} | |
// if is an object, compare the keys and values | |
if (typeof expected === "object" && typeof actual === "object") { | |
const expectedKeys = Object.keys(expected); | |
const actualKeys = Object.keys(actual); | |
if (expectedKeys.length !== actualKeys.length) { | |
failed++; | |
errorList.push( | |
new Error( | |
`Expected object with ${expectedKeys.length} keys but got ${actualKeys.length}` | |
) | |
); | |
} else { | |
for (let i = 0; i < expectedKeys.length; i++) { | |
const key = expectedKeys[i]; | |
if (expected[key] !== actual[key]) { | |
failed++; | |
errorList.push( | |
new Error( | |
`Expected ${expected[key]} but got ${actual[key]} at key ${key}` | |
) | |
); | |
} | |
} | |
} | |
return; | |
} | |
// if is a primitive, compare the values | |
if (expected !== actual) { | |
failed++; | |
errorList.push(new Error(`Expected ${expected} but got ${actual}`)); | |
} | |
}; | |
callback(assert); | |
console.log(`Total tests: ${counter} in ${name}, Failed: ${failed}`); | |
if (failed > 0) { | |
console.log("Errors in suite:"); | |
errorList.forEach((err, i) => console.log(`${i} - ${err.stack}`)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment