import { t, typeAsserts } from '../../index'; describe('object', () => { it('object first key', () => { expect.hasAssertions(); const schema = t.object({ name: t.string().optional(), age: t.number() }); expect( schema.validate({ // name: 'yinz', optional age: 30 }) ).toBe(true); expect( schema.validate({ // name: 'yinz', optional age: 30 }) ).toBe(true); expect( schema.validate({ name: 1, // error here age: 30 }) ).toBe(false); expect(() => typeAsserts(schema, { name: 1, // error here age: 30 }) ).toThrow('param.name should be string or undefined, but got 1'); expect(() => typeAsserts(schema, [])).toThrow('param should be object, but got a(n) array'); }); it('object not first key', () => { expect.hasAssertions(); const schema = t.object({ name: t.string().optional(), age: t.number() }); expect( schema.validate({ age: 30 }) ).toBe(true); expect( schema.validate({ age: '30' // error here }) ).toBe(false); expect(() => { typeAsserts(schema, { age: '30' // error here }); }).toThrow('param.age should be number, but got "30"'); }); it('optional object', () => { expect.hasAssertions(); const schema = t.object({ name: t.string(), age: t.number() }).optional(); expect(schema.validate(undefined)).toBe(true); expect(() => { typeAsserts(schema, undefined); }).not.toThrow(); expect(schema.validate({ name: 'yinz', age: 30 })).toBe(true); expect(() => { typeAsserts(schema, { name: 123, age: 30 }); }).toThrow('param.name should be string, but got 123'); }); it('default', () => { expect.hasAssertions(); const schema = t.object({ a: t.boolean().default(true) }); const data = {}; expect(schema.validate(data)).toBe(true); expect(data).toStrictEqual({ a: true }); }); it('fallback', () => { expect.hasAssertions(); const schema = t.object({ a: t.boolean().fallback(true) }); const data = { a: [] }; expect(schema.validate(data)).toBe(true); expect(data).toStrictEqual({ a: true }); }); it('special key', () => { expect.hasAssertions(); const schema1 = t.object({ '@@': t.string() }); expect(() => { typeAsserts(schema1, {}); }).toThrow('param["@@"] should be string, but got undefined'); const schema2 = t.object({ '-a': t.string() }); expect(() => { typeAsserts(schema2, {}); }).toThrow('param["-a"] should be string, but got undefined'); const schema3 = t.object({ 'a b': t.string() }); expect(() => { typeAsserts(schema3, {}); }).toThrow('param["a b"] should be string, but got undefined'); }); });