diff --git a/index.js b/index.js index e15bc0c5..ac8555f0 100644 --- a/index.js +++ b/index.js @@ -586,7 +586,8 @@ function buildArray (context, location) { ` functionCode += ` - if (!Array.isArray(obj)) { + const supportedTypedArrays = ['Uint8Array']; + if (!Array.isArray(obj) && !(obj != null && supportedTypedArrays.indexOf(obj.constructor.name) != -1)) { throw new TypeError(\`The value of '${schemaRef}' does not match schema definition.\`) } const arrayLength = obj.length diff --git a/test/anyof.test.js b/test/anyof.test.js index 03483329..3026d115 100644 --- a/test/anyof.test.js +++ b/test/anyof.test.js @@ -644,3 +644,31 @@ test('object with ref and validated properties', (t) => { const stringify = build(schema, { schema: externalSchemas }) t.equal(stringify({ id: 1, reference: 'hi' }), '{"id":1,"reference":"hi"}') }) + +test('anyOf with a TypedArray', (t) => { + t.plan(1) + + const anyOfSchema = { + type: 'object', + properties: { + maybeArray: { + anyOf: [{ + type: 'array', + items: { + type: 'number' + } + }, + { + type: 'string' + }] + } + } + } + const stringify = build(anyOfSchema) + + const typed = new Uint8Array(5) + typed.fill(10) + + const value = stringify({ maybeArray: typed }) + t.equal(value, '{maybeArray: [10,10,10,10,10]}') +}) diff --git a/test/oneof.test.js b/test/oneof.test.js index 491e9aef..61937e3c 100644 --- a/test/oneof.test.js +++ b/test/oneof.test.js @@ -490,3 +490,31 @@ test('all array items does not match oneOf types', (t) => { t.throws(() => stringify({ data: [null, false, true, undefined, [], {}] })) }) + +test('oneOf with a TypedArray', (t) => { + t.plan(1) + + const oneOfSchema = { + type: 'object', + properties: { + maybeArray: { + oneOf: [{ + type: 'array', + items: { + type: 'number' + } + }, + { + type: 'string' + }] + } + } + } + const stringify = build(oneOfSchema) + + const typed = new Uint8Array(5) + typed.fill(10) + + const value = stringify({ maybeArray: typed }) + t.equal(value, '{maybeArray: [10,10,10,10,10]}') +}) diff --git a/test/typesArray.test.js b/test/typesArray.test.js index cac9b09e..5441af0b 100644 --- a/test/typesArray.test.js +++ b/test/typesArray.test.js @@ -547,3 +547,24 @@ test('throw an error if none of types matches', (t) => { const stringify = build(schema) t.throws(() => stringify({ data: 'string' }), 'The value "string" does not match schema definition.') }) + +test('typedArray Uint8Array', (t) => { + t.plan(1) + const schema = { + type: 'object', + properties: { + arr: { + type: 'array', + items: { + type: 'number' + } + } + } + } + + const stringify = build(schema) + const arr = new Uint8Array(5) + arr.fill(5) + + t.equal(stringify({ arr }), '{"arr":[5,5,5,5,5]}') +})