validator/types/array.test.js

76 lines
2.1 KiB
JavaScript

/* eslint-disable no-undef */
const TypeArray = require('./array.js')
const TypeString = require('./string.js')
const TypeObject = require('./object.js')
describe('test validate schema type array', () => {
function throwFunc (val) {
return () => {
if (val) throw new Error(val)
}
}
it('test type array check array', async () => {
const arr = new TypeArray()
expect(throwFunc(arr.validate({}))).toThrow()
expect(throwFunc(arr.validate(false))).toThrow()
})
it('test type array with required', async () => {
const arr = new TypeArray().required()
throwFunc(arr.validate([1, 2]))
expect(throwFunc(arr.validate(undefined))).toThrow()
})
it('test type array with empty', async () => {
const arr = new TypeArray().empty()
throwFunc(arr.validate([]))
})
it('test type array without empty', async () => {
const arr = new TypeArray()
expect(throwFunc(arr.validate([]))).toThrow()
})
it('test type array with min length', async () => {
const arr = new TypeArray().min(2)
expect(() => new TypeArray().min()).toThrow()
expect(() => new TypeArray().min(false)).toThrow()
expect(() => new TypeArray().min(-1)).toThrow()
expect(() => new TypeArray().max(1).min(2)).toThrow()
throwFunc(arr.validate([1, 2]))
expect(throwFunc(arr.validate([1]))).toThrow()
})
it('test type array with max length', async () => {
const arr = new TypeArray().max(2)
expect(() => new TypeArray().max()).toThrow()
expect(() => new TypeArray().max(false)).toThrow()
expect(() => new TypeArray().min(5).max(3)).toThrow()
throwFunc(arr.validate([1]))
expect(throwFunc(arr.validate([1, 2, 3]))).toThrow()
})
it('test array contains value', async () => {
const arr = new TypeArray().items(new TypeString())
expect(throwFunc(arr.validate([1, 2, 3]))).toThrow()
throwFunc(arr.validate(['asd']))
const arr2 = new TypeArray().items(new TypeString(), new TypeObject())
expect(throwFunc(arr2.validate([123, true]))).toThrow()
throwFunc(arr2.validate(['asd', '33', {}]))
})
})