Last active
March 16, 2022 08:53
-
-
Save khaliqgant/4700a047107bf67b67c118ba89700bd1 to your computer and use it in GitHub Desktop.
[TS Interfaces in Tests] Using Typescript Interfaces In Tests using JSON schema #typescript #tests
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
/** | |
* | |
* Generate Schema | |
* @desc dynamically create the JSON Schema | |
* @see https://github.com/YousefED/typescript-json-schema#programmatic-use | |
* @return {Object} schema | |
* | |
*/ | |
function generateSchema (interfaceType: string): Object { | |
const program = TJS.getProgramFromFiles([resolve('./interfaces/admin/SchemaResponse.ts')], {strictNullChecks: true}); | |
const schema = TJS.generateSchema(program, interfaceType, {generateRequired: true}); | |
return schema; | |
} | |
/** | |
* | |
* Check | |
* @desc run a check against the JSON schema against the passed in JSON | |
* @see https://github.com/tdegrunt/jsonschema | |
* @param {Object} JSON | |
* @return {IValidationResponse} | |
* | |
*/ | |
function runCheck (json: Object, interfaceType: string): IValidationResponse { | |
const schema = generateSchema(interfaceType); | |
const v = new Validator(); | |
const result = v.validate(json, schema); | |
let isValid = result.errors.length > 0 ? false : true; | |
return {isValid: isValid, errors: result.errors}; | |
} | |
// Example interface and `interfaceType` is the particular exported interface, this is in a seperate file from the above | |
interface Foo { | |
[index: number]: FooArray; | |
} | |
interface Bar { | |
[index: number]: BarArray; | |
} | |
interface Baz { | |
[index: number]: BazArray; | |
} | |
export {Foo, Bar, Baz}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment