bdn-pocket
Version:
pocket tools for managing redux and redux-saga
129 lines (110 loc) • 2.94 kB
JavaScript
import test from 'ava'
import is from '@stamp/is'
import Types, { Type, number, string } from '../src/types'
test('Types', t => {
Object.keys(Types).forEach(
ty => {
t.true(
is.isFunction(Types[ty]),
`${ty} is a function`
)
t.true(
is.isStamp(Types[ty]),
`${ty} is a stamp`
)
}
)
})
test('Types#isValid required', t => {
const MyType = Type
.props({ type: 'myType' })
.methods({ isTypeOk() { return true }})
t.true(
MyType().required,
'by default, required is true'
)
const myReqType = MyType({ required: true, name: 'a' })
t.true(
myReqType.isValid({ a: 10 }),
'an object is validated if required prop is present'
)
t.true(
myReqType.isValid({ b: 10 }, 'b'),
'an object is validated if required prop is present with propName param overriding internal name'
)
t.throws(
() => { myReqType.isValid({b: ''}) },
Error,
'an object is not validated if required prop is not present'
)
const notReqtype = MyType({ required: false, name: 'a' })
t.true(
notReqtype.isValid({ b: '' }),
'an object is validated if not required prop is not present'
)
t.true(
notReqtype.isValid({ a: '' }),
'an object is validated if not required prop is present'
)
})
test('Types#isValid allowNull', t => {
const MyType = Type
.props({ type: 'myType' })
.methods({ isTypeOk() { return true }})
t.false(
MyType().allowNull,
'by default allowNull is false'
)
const myNullType = MyType({ allowNull: true, required: false, name: 'a' })
t.true(
myNullType.isValid({ a: 10 }),
'an object is validated if prop if prop val is set'
)
t.true(
myNullType.isValid({ a: null }),
'an object is validated if prop if prop val is set to null'
)
t.true(
myNullType.isValid({ a: undefined }),
'an object is validated if prop if prop val is set to undefined'
)
const notNullType = MyType({ allowNull: false, required: false, name: 'a' })
t.throws(
() => { notNullType.isValid({ a: null }) },
Error,
'an object is not validated if prop is null and allowNull is false'
)
t.true(
notNullType.isValid({ b: '' }),
'object is validated if allowNull is false and prop not present'
)
})
test('Types#isValid with defined types', t => {
const tOk = {
number: { f: number, v: 1 },
string: { f: string, v: 'a' },
}
const tNotOk = {
number: { f: number, v: 'a' },
string: { f: string, v: 1 },
}
Object.keys(tOk).forEach(
type => {
const s = tOk[type]
t.true(
s.f().isValid({ a: s.v }, 'a'),
'object is valid if prop has valid type'
)
}
)
Object.keys(tNotOk).forEach(
type => {
const s = tNotOk[type]
t.throws(
() => s.f().isValid({ a: s.v }),
Error,
'object is not valid if prop has not valid type'
)
}
)
})