Created
September 25, 2020 07:20
-
-
Save bartwttewaall/50d3641fde8d0afbe7c8f73bf8efdc02 to your computer and use it in GitHub Desktop.
Assert methods for testing purposes
This file contains hidden or 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
export const assert = (expectation: any, result: any, test: string = '') => { | |
if (typeof expectation !== typeof result) { | |
test += ` TYPE DIFFERENCE ${typeof expectation} compared to ${typeof result}`; | |
return output(expectation, result, test, false); | |
} | |
if (typeof expectation === 'object') { | |
return assertObj(expectation, result, test); | |
} else if (Array.isArray(expectation)) { | |
return assertArray(expectation, result, test); | |
} else { | |
const isSame = expectation === result ? true : false; | |
return output(expectation, result, test, isSame); | |
} | |
}; | |
function assertArray(expectation: any, result: any, test: string = '') { | |
if (expectation.length !== result.length) { | |
return output(expectation, result, test, false); | |
} | |
let isSame = true; | |
for (let i = 0; i < expectation.length; i++) { | |
if (expectation[i] !== result[i]) { | |
isSame = false; | |
break; | |
} | |
} | |
return output(expectation, result, test, isSame); | |
} | |
function assertObj(expectation: any, result: any, test: string = '') { | |
let isSame = true; | |
const keys1 = Object.keys(result); | |
const keys2 = Object.keys(expectation); | |
if (keys1.length !== keys2.length) { | |
isSame = false; | |
} | |
for (const prop in result) { | |
if (expectation[prop] !== result[prop]) { | |
isSame = false; | |
} | |
} | |
return output(expectation, result, test, isSame); | |
} | |
function output(expectation: any, result: any, test: string, isSame: boolean) { | |
if (isSame) { | |
return `::TEST ${test.toUpperCase()} PASSED::`; | |
} else { | |
if (typeof expectation === 'object') { | |
return `::TEST ${test.toUpperCase()} FAILED:: EXPECTED ${JSON.stringify(expectation)} but got ${JSON.stringify(result)}`; | |
} else { | |
return `::TEST ${test.toUpperCase()} FAILED:: EXPECTED ${expectation} but got ${result}`; | |
} | |
} | |
} | |
export default assert; | |
// assert('123'.length, 3, '3 chars'); //? | |
// assert('1234'.length, 3, '3 chars'); //? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment