validator/types/array.test.js

76 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-06-03 15:49:04 +00:00
/* eslint-disable no-undef */
const TypeArray = require('./array.js')
const TypeString = require('./string.js')
const TypeObject = require('./object.js')
2020-06-03 15:49:04 +00:00
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]))
2020-06-03 15:49:04 +00:00
expect(throwFunc(arr.validate(undefined))).toThrow()
})
it('test type array with empty', async () => {
const arr = new TypeArray().empty()
throwFunc(arr.validate([]))
2020-06-03 15:49:04 +00:00
})
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]))
2020-06-03 15:49:04 +00:00
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]))
2020-06-03 15:49:04 +00:00
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', {}]))
})
2020-06-03 15:49:04 +00:00
})