Skip to content

Instantly share code, notes, and snippets.

@khaliqgant
Last active March 16, 2022 08:53
Show Gist options
  • Save khaliqgant/4700a047107bf67b67c118ba89700bd1 to your computer and use it in GitHub Desktop.
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
/**
*
* 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