From 94659c257ebf7caa257cf08fcfed89542b364b0a Mon Sep 17 00:00:00 2001 From: Jason Quense Date: Fri, 6 Mar 2020 10:13:25 -0500 Subject: [PATCH] fix: array.ensure closes #343 --- src/array.js | 11 ++++++----- test/array.js | 12 ++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/array.js b/src/array.js index e66fead8f..045a35eb3 100644 --- a/src/array.js +++ b/src/array.js @@ -158,17 +158,18 @@ inherits(ArraySchema, MixedSchema, { }, ensure() { - return this.default(() => []).transform(val => { - if (this.isType(val)) return val; - return val === null ? [] : [].concat(val); + return this.default(() => []).transform((val, original) => { + // We don't want to return `null` for nullable schema + if (this._typeCheck(val)) return val; + return original == null ? [] : [].concat(original); }); }, compact(rejector) { let reject = !rejector ? v => !!v : (v, i, a) => !rejector(v, i, a); - return this.transform( - values => (values != null ? values.filter(reject) : values), + return this.transform(values => + values != null ? values.filter(reject) : values, ); }, diff --git a/test/array.js b/test/array.js index 5c3bec587..a09081702 100644 --- a/test/array.js +++ b/test/array.js @@ -174,6 +174,18 @@ describe('Array types', () => { inst.cast(a).should.equal(a); inst.cast(null).should.eql([]); + // nullable is redundant since this should always produce an array + // but we want to ensure that null is actually turned into an array + inst + .nullable() + .cast(null) + .should.eql([]); + + inst.cast(1).should.eql([1]); + inst + .nullable() + .cast(1) + .should.eql([1]); }); it('should pass resolved path to descendants', async () => {