import { expect, fsPath } from '../test'; import { Schema } from '..'; import { SchemaDefinition } from './SchemaDefinition'; const BASE = fsPath.resolve('./src/example'); describe('Schema', function() { this.timeout(5000); const schema = Schema.compile({ files: 'types/index.ts', basePath: BASE }); describe('construction', () => { it('resolves relative file paths', () => { const path = fsPath.resolve('./src/example/types/types.other.ts'); const schema = Schema.compile({ files: ['./src/example/types/types.ts', path], }); expect(schema.basePath).to.eql(undefined); expect(schema.files[0]).to.eql(fsPath.join(BASE, 'types/types.ts')); expect(schema.files[1]).to.eql(path); }); it('resolves base path', () => { const schema = Schema.compile({ basePath: './src/example', files: '/types/index.ts', }); expect(schema.basePath).to.eql(BASE); expect(schema.files[0]).to.eql(fsPath.join(BASE, '/types/index.ts')); }); it('throws if files do not exist', () => { const fn = () => Schema.compile({ files: '__NOT_EXIST__' }); expect(fn).to.throw(/does not exist/); }); it('throw if no files are passed', () => { expect(() => Schema.compile({ files: [] })).to.throw(); expect(() => Schema.compile({ files: '' })).to.throw(); expect(() => Schema.compile({ files: ' ' })).to.throw(); expect(() => Schema.compile({ files: ['', ' '] })).to.throw(); }); }); describe('schema generation', () => { it('for type (single)', () => { const res = schema.forType('IFoo'); const props = res.def.properties as any; expect(res.isValidSchema).to.eql(true); expect(res.def.type).to.eql('object'); expect(props.name.type).to.eql('string'); expect(res.def.required).to.eql(['age', 'name']); }); it('for types (plural)', () => { const res = schema.forType(['IFoo', 'IBar']); const defs = res.def.definitions as any; expect(res.isValidSchema).to.eql(true); expect(defs.IFoo.properties.name.type).to.eql('string'); expect(defs.IBar.properties.createdAt.type).to.eql('number'); }); it('error: no match', () => { const fn1 = () => schema.forType('INotExist'); const fn2 = () => schema.forType(['INope', 'INada']); expect(fn1).to.throw(/Failed to generate schema for symbol 'INotExist'/); expect(fn2).to.throw( /Failed to generate schema for symbol 'INope,INada'/, ); }); it('is not a valid schema', () => { const bogus = 'hello' as any; const def = new SchemaDefinition({ type: 'IFoo', def: bogus }); expect(def.isValidSchema).to.eql(false); }); it('schemaVersion', () => { const res = schema.forType('IFoo'); expect(res.schemaVersion).to.eql( 'http://json-schema.org/draft-07/schema#', ); }); }); describe('validate', () => { const foo = schema.forType('IFoo'); it('is valid', async () => { const res = foo.validate({ name: 'Sky', age: 30 }); expect(res).to.eql(true); }); it('is not valid', async () => { const res = foo.validate({ name: true }); expect(res).to.eql(false); }); }); });