Skip to content

Commit

Permalink
[changed] Don't throw on undefined values in cast()
Browse files Browse the repository at this point in the history
  • Loading branch information
jquense committed Jul 20, 2016
1 parent dbf3d9f commit 73858fe
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 12 deletions.
25 changes: 16 additions & 9 deletions src/mixed.js
@@ -1,4 +1,3 @@
import typeOf from 'type-name';
import has from 'lodash/has';

import { mixed as locale } from './locale';
Expand Down Expand Up @@ -133,15 +132,23 @@ SchemaType.prototype = {
return this
},

cast(value, opts = {}) {
let schema = this.resolve(opts)

let result = schema._cast(value, opts);

if (opts.assert !== false && !this.isType(result)) {
cast(value, options = {}) {
let resolvedSchema = this.resolve(options)
let result = resolvedSchema._cast(value, options);

if (
value !== undefined &&
options.assert !== false &&
resolvedSchema.isType(result) !== true
) {
let formattedValue = JSON.stringify(value);
let formattedResult = JSON.stringify(result);
throw new TypeError(
`Expected ${opts.path || 'field'} to be type: "${this._type}". ` +
`Got "${typeOf(value)}" instead.`
`The value of ${options.path || 'field'} could not be cast to a value ` +
`that satisfies the schema type: "${resolvedSchema._type}". \n\n` +
`attempted value: ${JSON.stringify(value)} \n` +
((formattedResult !== formattedValue)
? `result of cast: ${JSON.stringify(result)}` : '')
);
}

Expand Down
3 changes: 1 addition & 2 deletions test/helpers.js
@@ -1,10 +1,9 @@
import typeOf from 'type-name';

export let castAndShouldFail = (schema, value) => {
(()=> schema.cast(value))
.should.throw(
TypeError,
new RegExp(`Got "${typeOf(value)}" instead`, 'gi')
/The value of (.+) could not be cast to a value that satisfies the schema type/gi
)
}

Expand Down
1 change: 0 additions & 1 deletion test/string.js
Expand Up @@ -19,7 +19,6 @@ describe('String types', function(){
[null, null, schema.nullable()]
],
invalid: [
undefined,
null,
]
})
Expand Down
18 changes: 18 additions & 0 deletions test/yup.js
Expand Up @@ -12,6 +12,24 @@ describe('Yup', function(){
require('../lib')
})

it('cast should not assert on undefined', () => {
(() => string().cast(undefined))
.should.not.throw()
})

it('cast should assert on undefined cast results', () => {
(() => string().transform(() => undefined).cast('foo'))
.should.throw()
})

it('cast should respect assert option', () => {
(() => string().cast(null))
.should.throw();

(() => string().cast(null, { assert: false }))
.should.not.throw()
})

it('should do settled', function(){
return Promise.all([

Expand Down

0 comments on commit 73858fe

Please sign in to comment.