Skip to content

Commit 73858fe

Browse files
committed
[changed] Don't throw on undefined values in cast()
1 parent dbf3d9f commit 73858fe

File tree

4 files changed

+35
-12
lines changed

4 files changed

+35
-12
lines changed

src/mixed.js

+16-9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import typeOf from 'type-name';
21
import has from 'lodash/has';
32

43
import { mixed as locale } from './locale';
@@ -133,15 +132,23 @@ SchemaType.prototype = {
133132
return this
134133
},
135134

136-
cast(value, opts = {}) {
137-
let schema = this.resolve(opts)
138-
139-
let result = schema._cast(value, opts);
140-
141-
if (opts.assert !== false && !this.isType(result)) {
135+
cast(value, options = {}) {
136+
let resolvedSchema = this.resolve(options)
137+
let result = resolvedSchema._cast(value, options);
138+
139+
if (
140+
value !== undefined &&
141+
options.assert !== false &&
142+
resolvedSchema.isType(result) !== true
143+
) {
144+
let formattedValue = JSON.stringify(value);
145+
let formattedResult = JSON.stringify(result);
142146
throw new TypeError(
143-
`Expected ${opts.path || 'field'} to be type: "${this._type}". ` +
144-
`Got "${typeOf(value)}" instead.`
147+
`The value of ${options.path || 'field'} could not be cast to a value ` +
148+
`that satisfies the schema type: "${resolvedSchema._type}". \n\n` +
149+
`attempted value: ${JSON.stringify(value)} \n` +
150+
((formattedResult !== formattedValue)
151+
? `result of cast: ${JSON.stringify(result)}` : '')
145152
);
146153
}
147154

test/helpers.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
import typeOf from 'type-name';
21

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

test/string.js

-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ describe('String types', function(){
1919
[null, null, schema.nullable()]
2020
],
2121
invalid: [
22-
undefined,
2322
null,
2423
]
2524
})

test/yup.js

+18
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,24 @@ describe('Yup', function(){
1212
require('../lib')
1313
})
1414

15+
it('cast should not assert on undefined', () => {
16+
(() => string().cast(undefined))
17+
.should.not.throw()
18+
})
19+
20+
it('cast should assert on undefined cast results', () => {
21+
(() => string().transform(() => undefined).cast('foo'))
22+
.should.throw()
23+
})
24+
25+
it('cast should respect assert option', () => {
26+
(() => string().cast(null))
27+
.should.throw();
28+
29+
(() => string().cast(null, { assert: false }))
30+
.should.not.throw()
31+
})
32+
1533
it('should do settled', function(){
1634
return Promise.all([
1735

0 commit comments

Comments
 (0)