Last active
April 15, 2022 12:21
-
-
Save nobodyme/7079bc637e2c16d8336e84ca4893c4cc to your computer and use it in GitHub Desktop.
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
function _object_equals(object_1, object_2) { | |
const keys = new Set([ | |
...Object.keys(object_1), | |
...Object.keys(object_2) | |
]); | |
for (const key of keys) { | |
// if one is instance of object, check if both are | |
if (object_2[key] instanceof Object || object_1[key] instanceof Object) { | |
if (object_2[key] instanceof Object && object_1[key] instanceof Object) { | |
const subcheck = _object_equals(object_1[key], object_2[key]); | |
if (!subcheck) { | |
return (false); | |
} | |
continue; | |
} | |
return (false); | |
} | |
if (object_2[key] !== object_1[key]) { | |
return (false); | |
} | |
} | |
return (true); | |
} | |
/** | |
* @param {object containing input and output} test_cases | |
* @param {function to be tested} test_function | |
* | |
*/ | |
function run_tests(test_cases, test_function) { | |
let passed = true; | |
for (const each_test of test_cases) { | |
const input = JSON.parse(JSON.stringify(each_test['input'])); | |
const result = test_function(...each_test['input']); | |
const expected = each_test['output']; | |
if (typeof result !== typeof expected) { | |
passed = false; | |
console.log(`FAILED test for ${JSON.stringify(input)}, expected ${JSON.stringify(expected)} got ${JSON.stringify(result)}`); | |
continue; | |
} | |
/** | |
* if result is not an object, use the direct equality operator | |
* else use our _object_equals method | |
*/ | |
if (typeof result !== 'object') { | |
if (result !== expected) { | |
passed = false; | |
console.log(`FAILED test for ${JSON.stringify(input)}, expected ${JSON.stringify(expected)} got ${JSON.stringify(result)}`); | |
} | |
} else if (_object_equals(result, expected) === false) { | |
passed = false; | |
console.log(`FAILED test for ${JSON.stringify(input)}, expected ${JSON.stringify(expected)} got ${JSON.stringify(result)}`); | |
} | |
} | |
if (passed === true) { | |
console.log('Tests passed'); | |
} | |
} | |
module.exports = { | |
run_tests | |
}; | |
/** | |
* Sample Usage: | |
* | |
* const tests = [ | |
* { input: 'sakhfkg', output: false }, | |
* { input: 'abhvb', output: false }, | |
* { input: 'ssaf', output: false }, | |
* ]; | |
* | |
* run_tests(tests, functionNameToTest); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment