import { t, typeAsserts } from '../../index'; describe('tuple', () => { it('tuple', () => { expect.hasAssertions(); const schema = t.tuple(t.string(), t.number(), t.object()); expect(schema.validate([123, 123, 123])).toBe(false); expect(() => { typeAsserts(schema, [123, 123, 123]); }).toThrow('param[0] should be string, but got 123\nparam[2] should be object, but got 123'); }); it('optional tuple', () => { expect.hasAssertions(); const schema = t.tuple(t.string(), t.number(), t.object()).optional(); expect(schema.validate(undefined)).toBe(true); expect(schema.validate({})).toBe(false); expect(() => { typeAsserts(schema, {}); }).toThrow('param should be array or undefined, but got a(n) object'); }); it('tuple fixed length', () => { expect.hasAssertions(); const schema = t.tuple(t.string(), t.number(), t.object()); expect(schema.validate(['str', 123, {}])).toBe(true); expect(schema.validate(['str', 123])).toBe(false); expect(() => { typeAsserts(schema, ['str', 123]); }).toThrow('the length of param should be greater than or equal to 3'); }); it('optional length', () => { expect.hasAssertions(); const schema = t.tuple(t.string(), t.number(), t.object().optional()); expect(schema.validate(['str', 123, {}])).toBe(true); expect(schema.validate(['str', 123])).toBe(true); expect(schema.validate(['str'])).toBe(false); expect(() => { typeAsserts(schema, ['str']); }).toThrow('the length of param should be greater than or equal to 2'); }); it('optional length should ignore optional items before item without optional', () => { expect.hasAssertions(); const schema = t.tuple(t.string().optional(), t.number(), t.object().optional()); expect(schema.validate(['str', 123, {}])).toBe(true); expect(schema.validate(['str', 123])).toBe(true); expect(schema.validate(['str'])).toBe(false); expect(schema.validate([])).toBe(false); expect(() => { typeAsserts(schema, ['str']); }).toThrow('the length of param should be greater than or equal to 2'); }); it('fallback', () => { expect.hasAssertions(); const schema = t.tuple(t.string().fallback('str')); const data = [123]; expect(schema.validate(data)).toBe(true); expect(data).toStrictEqual(['str']); }); it('default', () => { expect.hasAssertions(); const schema = t.tuple(t.string().default('str')); const data: unknown[] = []; expect(schema.validate(data)).toBe(true); expect(data).toStrictEqual(['str']); }); });